Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib savefig cuts off pyplot table

I want to make some summarizing visualization + statistics of a data column. I want to combine two or more subplots with a descriptive table and save the figure locally. However, when saving the plot, a part of the table gets cropped.

When I do the following

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

column=np.random.normal(size=10000)
df=pd.DataFrame(column, columns=["Price"])

summary = (
        df.describe()
        .append((df.isnull().sum()/len(df)*100)
        .rename('nans %'))
        .iloc[:,0].to_frame()
        )
fig, (ax_distplot) = plt.subplots(1, 1, figsize=(25, 12))

#Distplot with summarizing table
sns.distplot(df.loc[:,"Price"], hist=True, bins=30, kde=False, ax=ax_distplot)
ax_distplot.set(ylabel='Count')
tab = ax_distplot.table(cellText=np.around(summary.values, decimals=2), 
                        rowLabels=summary.index, 
                        colLabels=summary.columns, loc="right", 
                        bbox=[1.15, .2, 0.25, 0.8])

I get: What it should be

When saving it locally with the following command

plt.savefig("Price.pdf", bbox_inches="tight")

Yields: Cutted off table

I have tried

plt.subplots_adjust(right=0.85)

without any luck.

like image 963
Nicolai Iversen Avatar asked May 28 '26 14:05

Nicolai Iversen


1 Answers

This is an error in how the table bounding box is calculated. You may open an issue about it.

In the meantime drawing the canvas manually (and hence twice) solves this.

fig.canvas.draw()
plt.savefig("price.png", bbox_inches="tight")
like image 177
ImportanceOfBeingErnest Avatar answered May 30 '26 03:05

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!