matplotlib:如果我设置了图高度,则x传奇被切断

otm*_*ger 4 python plot matplotlib

我试图fig1.set_size_inches(5.5,3)在python上设置图形大小,但是图形产生的图形中x标签不是完全可见的.这个数字本身就有我需要的尺寸,但看起来里面的轴太高了,x标签就不再合适了.

这是我的代码:

fig1 = plt.figure()
fig1.set_size_inches(5.5,4)
fig1.set_dpi(300)
ax = fig1.add_subplot(111)
ax.grid(True,which='both')
ax.hist(driveDistance,100)
ax.set_xlabel('Driven Distance in km')
ax.set_ylabel('Frequency')
fig1.savefig('figure1_distance.png')
Run Code Online (Sandbox Code Playgroud)

这是结果文件:

5.5x3英寸的图像

Kor*_*rem 8

您可以订购保存方法以考虑x标签的艺术家.

这是通过bbox_extra_artists和紧密布局完成的.结果代码将是:

import matplotlib.pyplot as plt
fig1 = plt.figure()
fig1.set_size_inches(5.5,4)
fig1.set_dpi(300)
ax = fig1.add_subplot(111)
ax.grid(True,which='both')
ax.hist(driveDistance,100)
xlabel = ax.set_xlabel('Driven Distance in km')
ax.set_ylabel('Frequency')
fig1.savefig('figure1_distance.png', bbox_extra_artists=[xlabel], bbox_inches='tight')
Run Code Online (Sandbox Code Playgroud)

  • 实际上,可能不需要变量`xlabel`.只将最后一行代码更改为`fig1.savefig('figure1_distance.png',bbox_inches ='tight')`才能完成工作 (3认同)
  • 在子图中你也可以使用`fig1.tight_layout()`代替`bbox_inches ='tight' (2认同)