qua*_*ant 4 python python-3.x plotly plotly-python
我有一个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
Run Code Online (Sandbox Code Playgroud)
我正在使用绘制直方图,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)
Run Code Online (Sandbox Code Playgroud)
是否可以在每个直方图旁边添加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")
Run Code Online (Sandbox Code Playgroud)
最后,您可以按照pdf此处的.write_image()说明保存完整的图(6 个图表) 。您需要安装实用程序才能执行此操作。输出将如下所示(您当然可以自定义它):kaleidoorca
如果您需要将每个图形+表格保存在 PDF 的单独页面上,您可以利用该PyPDF2库。因此,首先,您将每个图形+表格保存为单个 PDF(如上所述,但您将保存与您拥有的列数一样多的 PDF 文件,而不是 1),然后您可以按照此答案中的说明进行操作合并它们: