将 for 循环中生成的所有 Plotly 图下载为 pdf 的代码?

问题描述 投票:0回答:1

我正在为 Plotly 中的 500 个机构生成 7 个图表。我可以将每个图表下载为 png,然后将其转换为 pdf。但这很耗时,而且我确信有一种我想不出的更简单的方法。我想写一行代码,如果可能的话,可以将下面列出的所有图表生成一个 pdf。我的代码如下:

count=0
for o in new_df['origin'].unique()[20:21]:
    origin_df=new_df.loc[new_df['origin']==o]
    graph1a()
    graph2()
    graph3a()
    graph4()
    graph5()
    graph6a()
    graph777()
python for-loop pdf graph plotly
1个回答
0
投票

有关creating pdf reports的情节文档中有一个部分。假设您的函数

graph1a, ... graph777
都返回 plotly 数字,您可以执行以下操作:

import plotly.plotly as py
import base64

from IPython.display import display, HTML

width = 600
height = 600

template = (''
    '<img style="width: {width}; height: {height}" src="data:image/png;base64,{image}">'
    '{caption}'                              # Optional caption to include below the graph
    '<br>'
    '<hr>'
'')

# A collection of Plotly graphs
count=0
for n, o in enumerate(new_df['origin'].unique()[20:21]):
    origin_df=new_df.loc[new_df['origin']==o]
    figures = [
        graph1a(),
        graph2(),
        graph3a(),
        graph4(),
        graph5(),
        graph6a(),
        graph777(),
    ]

    # Generate their images using `py.image.get`
    images = [base64.b64encode(py.image.get(figure, width=width, height=height)).decode('utf-8') for figure in figures]

    report_html = ''
    for image in images:
        _ = template
        _ = _.format(image=image, caption='', width=width, height=height)
        report_html += _

    display(HTML(report_html))
    convert_html_to_pdf(report_html, f'report-{n}.pdf')
© www.soinside.com 2019 - 2024. All rights reserved.