2012-03-10 131 views
24

我正在尝试使用matplotlib为图例创建一个图例。我可以看到情节正在创建,但图像边界不允许显示整个图例。我的matplotlib.pyplot图例正在被切断

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

+0

[This answer](https://stackoverflow.com/a/43439132/4124317)概述了几种可用于使图例出现在图形边界内的技术。 – ImportanceOfBeingErnest 2017-10-11 22:03:45

回答

16

正如指出的亚当,你需要在你的图的侧面空间。 如果你想微调所需的空间,你可能想看看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

+50

我知道matplotlib喜欢吹嘘所有东西都在用户的控制之下,但是与传说有关的整个事情都是一件好事。如果我把传说放在外面,我明显地希望它仍然可见。该窗口应该只是适应自己而不是创建这个巨大的缩放麻烦。至少应该有一个默认的True选项来控制这种自动缩放行为。强迫用户通过一些荒谬的重新渲染,试图以控制的名义获得正确的比例数字,完成了相反的事情。 – Elliot 2013-01-02 21:43:45

+0

@strpeter在他的回答中提供了一个自动的解决方案,对我来说工作得非常好。 – 2017-02-27 12:21:38

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

5

在这里是使空间的另一种方式(收缩轴):

# 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

15

Eventhough它是晚,我想指的,如果你有兴趣的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 as-well兼容,而其他人不是!
+1

适合我。谢谢! – weefwefwqg3 2017-05-27 19:02:45

+0

谢谢!这工作得很好w /必要的小修改。 – 2017-08-08 23:27:25

+0

@CarlodelMundo:您的情况需要进行哪些修改?感谢您与我们分享。 – strpeter 2017-08-10 07:47:23