首页 > 解决方案 > 如何在 plotly express 图表旁边添加一个表格并将它们保存为 pdf

问题描述

我有一个dataframe

              a            b   c
0   2610.101010 13151.030303   33.000000
1   1119.459459 5624.216216    65.777778
2   3584.000000 18005.333333    3.000000
3   1227.272727 5303.272727    29.333333
4   1661.156504 8558.836558   499.666667

我正在使用以下简单代码绘制直方图,并且还使用以下简单代码plotly.express打印表格:describe

import plotly.express as px
for col in df.columns:
    px.histogram(df, x=col, title=col).show()
    print(df[col].describe().T)

是否可以在每个直方图旁边添加describe并将所有图(连同它们各自的直方图)保存在一个 pdf 中?

标签: pythonpython-3.xplotlyplotly-python

解决方案


实现此目的的一种方法是创建一个子图网格,大小为 n_columns * 2(一个用于直方图,一个用于表。例如:

from plotly.subplots import make_subplots

titles = [[f"Histogram of {col}", f"Stats of {col}"] for col in df.columns]
titles = [item for sublist in titles for item in sublist]

fig = make_subplots(rows=3, 
                    cols=2, 
                    specs=[[{"type": "histogram"}, {"type": "table"}]] *3,
                    subplot_titles=titles)

for i, col in enumerate(df.columns):
    fig.add_histogram(x=df[col], 
                      row=i+1, 
                      col=1)
    fig.add_table(cells=dict(
                        values=df[col].describe().reset_index().T.values.tolist()
                        ), 
                  header=dict(values=['Statistic', 'Value']), 
                  row=i+1, 
                  col=2
                 )
fig.update_layout(showlegend=False) 
fig.show()

fig.write_image("example_output.pdf")

最后,您可以按照此处pdf.write_image()说明保存完整的无花果(共 6 个图表)。您将需要安装或实用程序来执行此操作。输出将如下所示(您当然可以自定义它):kaleidoorca

在此处输入图像描述

如果您需要将每个图形 + 表格保存在 PDF 的单独页面上,您可以利用该PyPDF2库。因此,首先,您将每个图形 + 表格保存为单个 PDF(如上所述,但您将保存与您拥有的列数一样多的 PDF 文件,而不是 1),然后您可以按照此答案中的说明操作合并它们:


推荐阅读