python - 如何在 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 中?
解决方案
实现此目的的一种方法是创建一个子图网格,大小为 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 个图表)。您将需要安装或实用程序来执行此操作。输出将如下所示(您当然可以自定义它):kaleido
orca
如果您需要将每个图形 + 表格保存在 PDF 的单独页面上,您可以利用该PyPDF2
库。因此,首先,您将每个图形 + 表格保存为单个 PDF(如上所述,但您将保存与您拥有的列数一样多的 PDF 文件,而不是 1),然后您可以按照此答案中的说明操作合并它们:
推荐阅读
- azure-devops - How to connect build agent to PostgreSQL database
- django - Django - 从单个 API 保存多个模型
- unit-testing - 传入对象时,xUnit Moq 设置未能检测到方法
- python - 从 Tkinter 画布保存时图像不会清除
- snowflake-cloud-data-platform - 是否可以选择在雪花表上强制分区
- spring-boot - 使用@Async 和@Transactional 方法springboot
- c - 由“写入内存访问”引起的错误
- vue.js - 如何将表格单元格内的div移动到另一个单元格vuejs
- python - 如何通过 API Gateway 在 AWS Lambda 中将“pdf”和“html”文件作为“事件”传递?
- c# - 从另一个网站导航时 RedirectToAction 不起作用