在matplotlib中,轴Axes的位置以标准化图形坐标指定,可能发生的情况是轴标签、标题、刻度标签等等会超出图形区域,导致显示不全。Matplotlib v1.1 引入了一个新的命令tight_layout(),作用是自动调整子图参数,使之填充整个图像区域。
tight_layout在plt.savefig的调用方式相对比较稳定,我们将plt.show()函数替换为plt.savefig函数,替换后会在本地另外为png图片,该图片中子图填充了整个图像区域。
plt.savefig('fig.png', bbox_inches='tight') # 替换 plt.show()
import matplotlib.pyplot as plt from matplotlib.pyplot import MultipleLocator plt.set_loglevel('WARNING') plt.rcParams['font.family'] = 'Songti SC' # plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.figure() plt.plot(list_x, list_y, label="label") plt.xticks(rotation=80) plt.title(f'title') ax = plt.gca() x_major_locator = MultipleLocator(2) ax.xaxis.set_major_locator(x_major_locator) plt.legend() plt.xlabel("xlabel") plt.ylabel('ylabel') plt.grid(True) plt.axis('tight') plt.tight_layout() plt.savefig('fig.png', dpi=200) # plt.show() plt.close()