python - Matplotlib savefig 截断pyplot表

标签 python pandas matplotlib

我想做一些数据列的可视化总结+统计。 我想将两个或多个子图与描述性表格组合起来,并将图形保存在本地。 但是,保存绘图时,表格的一部分会被裁剪。

当我执行以下操作时

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

我得到: What it should be

使用以下命令将其保存到本地时

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

产量: Cutted off table

我已经尝试过

plt.subplots_adjust(right=0.85)

没有任何运气。

最佳答案

这是计算表格边界框的方式错误。您可以提出一个有关它的问题。

同时手动绘制 Canvas (因此两次)可以解决这个问题。

fig.canvas.draw()
plt.savefig("price.png", bbox_inches="tight")

关于python - Matplotlib savefig 截断pyplot表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328353/

相关文章:

python - 如何将所有属性导入 numpy 模块?

python - 当情况并非如此时,Pylint-django 会引发有关 Django 未配置的错误(VSCode)

python - 19 位长整数的截断问题

Python。从 data.frame 获取结构

python - 数据对齐后无法导出为 CSV

python - Matplotlib:获取子图位置值(hspace,wspace,..)

python - SqlAlchemy:检查一个对象是否处于任何关系中(或_(object.relationship1.contains(otherObject),object.relationship2.contains(otherObject))

python - 如何使用 Pycharm 调试 python 脚本?

python - 使用 matplotlib 从 pcolormesh 动画四边形网格

python - 如何平滑python中图形中的线条?