matplotlib:设置图高后,x轴图例被裁剪
我在用Python设置图形大小,代码是 fig1.set_size_inches(5.5,3)
,但是生成的图表里,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')
这是生成的结果文件:
2 个回答
2
如果我在创建图形的时候用 figsize
和 dpi
来初始化,效果就很好。这两个参数可以通过 kwargs
来设置:
from numpy import random
from matplotlib import pyplot as plt
driveDistance = random.exponential(size=100)
fig1 = plt.figure(figsize=(5.5,4),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')
9
你可以让保存方法考虑到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')