我正在尝试使用 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.)
这会产生:
尽管已经晚了,我想参考最近推出的一个不错的替代方案:
如果您对
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')
我还想参考更详细的答案:将 matplotlib 图例移到轴之外会使其被图形框截断
plt.subplots
兼容,而其他则不兼容!正如 Adam 所指出的,您需要在图表的一侧留出空间。 如果你想微调所需的空间,你可能需要查看 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()
以及生成的图像:
只需使用
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
版本中引入的,并且可以很好地完成工作。
这是另一种创造空间的方法(缩小轴):
# 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 的因子将为图例腾出空间。
此代码引用自:如何将图例从绘图中取出
编辑:@gcalmettes 发布了更好的答案。
也许应该使用他的解决方案而不是下面所示的方法。
尽管如此,我还是会离开这个,因为有时它有助于了解不同的做事方式。
如图例绘图指南所示,您可以为另一个子图腾出空间并将图例放在那里。
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()
产品:
使用
bbox_inches='tight'
选项
plt.savefig('my_plot.svg', bbox_inches='tight')
将图例调用实例存储到变量中。例如:
rr = sine_curve_plot.legend(loc=(0.0,1.1))
然后,将
bbox_extra_artists
、bbox_inches
关键字参数包含到 plt.savefig
。即:
plt.savefig('output.pdf', bbox_inches='tight', bbox_extra_artists=(rr))
bbox_extra_artists
接受一个可迭代对象,因此您可以在其中包含尽可能多的 legend
实例。 bbox_extra_artists
自动告诉 plt 覆盖传递到 bbox_extra_artists
的所有额外信息。
免责声明:
loc
变量仅定义图例的位置,您可以调整这些值以获得更好的定位灵活性。当然,像upper left
、upper right
等字符串也是有效的。