如何在Matplotlib中扩展图形底部的边距?

74
以下截图显示我的x轴。 图片描述 我添加了一些标签并将它们旋转90度以更好地阅读它们。 但是,pyplot截断了底部,使我无法完全读取标签。 如何扩展底边距以便查看完整标签?
6个回答

90

2
你还可以在subplots 中传递 tight_layout=True,它会产生相同的效果。 - tacaswell
有没有一种方法可以在不使用“tight_layout”和“subplots”的情况下完成这个操作?也就是说,如果只是创建一个图形并通过“plt.plot(...)”添加一个绘图。我之所以问这个问题,是因为我正在尝试为电影创建多个图形,如果使用“subplots”和/或“tight_layout”,标题和轴标签会晃动。任何帮助都将不胜感激。 - Wolpertinger
1
@Wolpertinger: fig = plt.figure(); fig.add_axes(...); https://matplotlib.org/api/_as-gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.add_axes - Paul H
subplots_adjust 部分地为我解决了问题,在图例被切断的情况下,它增加了一些空间在图形的顶部:top=0.75 的效果不够理想,而 top=1.5 奇怪地似乎没有任何效果。在这种特殊情况下,tight_layout 似乎没有任何效果。 - bli

27

我使用过的一个快速解决方案是直接使用pyplot的自动tight_layout方法,该方法可在Matplotlib v1.1及以上版本中使用:

plt.tight_layout()

在显示图表之前(plt.show()),但在对轴进行操作(如刻度标签旋转等)之后,可以立即调用此方法。
这种便利方法避免了对子图的单独处理。
其中plt是标准pyplot:import matplotlib.pyplot as plt

3
好的回答。值得注意的是,“但在你的操作之后”这个评论非常重要。否则,你的标题可能会像我的一样被截断。 - phantomraa

15
fig.savefig('name.png', bbox_inches='tight')

对我来说,这是最好的选择,因为它不会减小剧情的规模,与其他选项相比。
fig.tight_layout()

10

Subplot-adjust对我没有用,因为整个图形会随着标签仍然超出边界而重新调整大小。

我发现的一种解决方法是始终将y轴保持在最高或最低y值的某个余量上:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,y1 - 100 ,y2 + 100))

2
这是我在这里找到的唯一有效的解决方案。 - Josh
axis()函数指定了坐标轴的视口,因此不清楚为什么使用plt.axis()会有助于位于坐标轴之外的标签...似乎更合理的期望是从plt.figure()中找到解决方法。 - PatrickT

1
fig, ax = plt.subplots(tight_layout=True)

0

这有点复杂,但它提供了一个通用而整洁的解决方案。

import numpy as np
value1 = 3

xvalues = [0, 1, 2, 3, 4]
line1 = [2.0, 3.0, 2.0, 5.0, 4.0]
stdev1 = [0.1, 0.2, 0.1, 0.4, 0.3]

line2 = [1.7, 3.1, 2.5, 4.8, 4.2]
stdev2 = [0.12, 0.18, 0.12, 0.3, 0.35]

max_times = [max(line1+stdev1),max(line2+stdev2)]
min_times = [min(line1+stdev1),min(line2+stdev2)]

font_size = 25

max_total = max(max_times)
min_total = min(min_times)

max_minus_min = max_total - min_total

step_size = max_minus_min/10
head_space = (step_size*3) 


plt.figure(figsize=(15, 15))
plt.errorbar(xvalues, line1, yerr=stdev1, fmt='', color='b')

plt.errorbar(xvalues, line2, yerr=stdev2, fmt='', color='r')
plt.xlabel("xvalues", fontsize=font_size)
plt.ylabel("lines 1 and 2 Test "+str(value1), fontsize=font_size)
plt.title("Let's leave space for the legend Experiment"+ str(value1), fontsize=font_size)
plt.legend(("Line1", "Line2"), loc="upper left", fontsize=font_size)
plt.tick_params(labelsize=font_size)
plt.yticks(np.arange(min_total, max_total+head_space, step=step_size) )
plt.grid()
plt.tight_layout()

结果: 带有图例的绘图,字体足够大,网格线。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接