我的matplotlib.pyplot传奇正在被切断

时间:2012-03-10 23:27:01

标签: python matplotlib

我正在尝试使用matplotlib创建一个带有图例的图表。我可以看到正在创建绘图,但图像边界不允许显示整个图例。

lines = []
ax = plt.subplot(111)
for filename in args:
    lines.append(plt.plot(y_axis, x_axis, colors[colorcycle], linestyle='steps-pre', label=filename))
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

这会产生: enter image description here

5 个答案:

答案 0 :(得分:27)

虽然现在已经很晚了,但我想引用一个不错的最近推出的替代方案:

新的matplotlib功能:紧密的边界框

如果您对plt.savefig的输出文件感兴趣:在这种情况下,标志bbox_inches='tight'是您的朋友!

import matplotlib.pyplot as plt

fig = plt.figure(1)
plt.plot([1, 2, 3], [1, 0, 1], label='A')
plt.plot([1, 2, 3], [1, 2, 2], label='B')
plt.legend(loc='center left', bbox_to_anchor=(1, 0))

fig.savefig('samplefigure', bbox_inches='tight')

Output file: samplefigure.png

我还想提一个更详细的答案:Moving matplotlib legend outside of the axis makes it cutoff by the figure box

优点

  • 无需调整实际数据/图片。
  • 它与plt.subplots兼容,而其他人则不兼容!
  • 它至少适用于最常用的输出文件,例如: png,pdf。

答案 1 :(得分:19)

正如亚当指出的那样,你需要在图表的一侧留出空间。 如果要微调所需的空间,可能需要查看matplotlib.pyplot.artist的add_axes方法。

以下是一个快速示例:

import matplotlib.pyplot as plt
import numpy as np

# some data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# plot of the data
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])
ax.plot(x, y1,'-k', lw=2, label='black sin(x)')
ax.plot(x, y2,'-r', lw=2, label='red cos(x)')
ax.set_xlabel('x', size=22)
ax.set_ylabel('y', size=22)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

以及生成的图片:image

答案 2 :(得分:6)

这是制造空间的另一种方式(收缩轴):

# get the current axis
ax = plt.gca()
# Shink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

其中0.8将轴的宽度缩放20%。在我的win7 64机器上,使用大于1的因子将为图例提供空间,如果它在图表之外。

此代码引自:How to put the legend out of the plot

答案 3 :(得分:1)

编辑:@gcalmettes发布了a better answer 应该使用他的解决方案而不是下面显示的方法 尽管如此,我会留下这个,因为它有时会有助于看到不同的做事方式。


the legend plotting guide所示,您可以为另一个子情节腾出空间并将图例放在那里。

import matplotlib.pyplot as plt
ax = plt.subplot(121) # <- with 2 we tell mpl to make room for an extra subplot
ax.plot([1,2,3], color='red', label='thin red line')
ax.plot([1.5,2.5,3.5], color='blue', label='thin blue line')
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()

产地:

enter image description here

答案 4 :(得分:0)

只需使用plt.tight_layout()

import matplotlib.pyplot as plt
    
fig = plt.figure(1)
plt.plot([1, 2, 3], [1, 0, 1], label='A')
plt.plot([1, 2, 3], [1, 2, 2], label='B')
plt.legend(loc='center left', bbox_to_anchor=(1, 0))

plt.tight_layout()

这可能是在较新的matplotlib版本中引入的,可以很好地完成工作。