【问题标题】:How to add a table next a plotly express chart and save them to a pdf如何在 plotly express 图表旁边添加一个表格并将它们保存为 pdf
【发布时间】:2021-02-05 11:19:04
【问题描述】:

我有一个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 中?

【问题讨论】:

标签: python python-3.x plotly plotly-python


【解决方案1】:

实现此目的的一种方法是创建一个子图网格,大小为 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")

最后,您可以使用.write_image() 将完整的无花果(共6 个图表)保存为pdf,如here 所述。您需要安装 kaleidoorca 实用程序才能执行此操作。输出将如下所示(您当然可以自定义):

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

【讨论】:

  • 我希望每个直方图及其对应的表格都位于 pdf 的单独页面上,因为如果你想绘制例如这个解决方案会有问题。 10 列,对吧?
  • @quant 这难道不符合这一点:Is it possible to add next to each histogram the describe and save all the plots (together with their respective histograms) in a single pdf?如果没有,抱歉打扰您,如果有,请投票并接受此答案,并提出一个新问题来处理上述细节。
  • @quant write_image 来自 plotly 在这方面并没有给你太多的灵活性。正如您所说,该图将保存为单个 PDF 页面。我在最后添加了一段解释你如何做到这一点。本质上,您可以为每个图形+表格创建+保存fig作为pdf格式,而不是创建1个fig。然后您可以使用 PyPDF2 包将所有文件连接成一个 PDF 文件,其中每一行是一页。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2019-12-20
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多