quant
quant

Reputation: 4482

How to add a table next a plotly express chart and save them to a pdf

I have a 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

and I am plotting histograms using plotly.express and I am also printing a describe table with the following simple code:

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

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 ?

Upvotes: 4

Views: 4300

Answers (1)

tania
tania

Reputation: 2305

One way to achieve this is by creating a subplot grid, the size of n_columns * 2 (one for the histogram and one for the table. For example:

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")

In the end, you can save the full fig (6 charts together) as pdf using .write_image() as explained here. You will need to install kaleido or orca utilities to do so. The output will look like this (you can of course customize it):

enter image description here

If you need to save each graph + table on a separate page of the PDF, you can take advantage of the PyPDF2 library. So, first, you would save each graph + table as a single PDF (as described above, but you would save as many PDF files as numbers of columns you have, not 1), and then you could follow the instructions from this answer to merge them:

Upvotes: 5

Related Questions