x 轴标签在保存的图像上被裁剪

问题描述 投票:0回答:3

因此,我尝试在数据上绘制条形图,其中

x
是用户名(字符串),并且每个
x
足够长以相互重叠,因此我必须旋转
x
标签。那里没问题。但是,导出绘图结果时,导出图像上的
x
标签会被裁剪。我尝试使用
plt.tight_layout()
并成功了,但它改变了情节的外观。代码与此类似


from matplotlib import pyplot as plt

x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]

plt.bar(x, y)

plt.xticks(rotation = 90) 
plt.savefig('a.png')

plt.show()

导出图像:

我希望它看起来像这样(通过使用 jupyter 笔记本并手动保存输出图像得到这个):

那么如何做到这一点?

python matplotlib plot data-visualization savefig
3个回答
2
投票

您可以尝试使用 rcParams 大小设置和

plt.subplots_adjust
设置,直到获得所需的图像。

import matplotlib.pyplot as plt
x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]

plt.rcParams["figure.figsize"] = (5,10)
plt.bar(x, y)
plt.xticks(rotation = 90) 
plt.subplots_adjust(top=0.925, 
                    bottom=0.20, 
                    left=0.07, 
                    right=0.90, 
                    hspace=0.01, 
                    wspace=0.01)
plt.savefig('a.png')
plt.show()

2
投票

所以我通过将

Bbox
实例分配给
bbox_inches
函数上的
plt.savefig()
参数得到了另一个答案。通过这个
Bbox
,我们可以定义我们保存的图形 (
xmin
) 的
ymin
xmax
ymax
Bbox([[xmin, ymin],[xmax, ymax]])
。默认值为
xmin=0
ymin=0
xmax=figure_width
ymax=figure_height

如果问题出在保存的图形的底部,我们只需配置(降低)

ymin


import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

x= ['abc', 'ronaldo', 'melon_killer_123456']
y= [1, 2, 3]

plt.bar(x, y)
plt.xticks(rotation = 90) 
plt.savefig('a.png', bbox_inches=Bbox([[0,-2],fig.get_size_inches()]))
plt.show()

P.s

fig.get_size_inches()
给我们一份无花果尺寸列表


0
投票

此链接提供了有关其原因的有用信息以及一些建议的解决方法。

在保存图形或将参数 bbox_inches='tight' 添加到 .savefig() 之前调用 fig.tight_layout() 在我的情况下可以避免裁剪seaborn热图上的 y 轴标签

© www.soinside.com 2019 - 2024. All rights reserved.