我有一系列20幅图(不是子图)要在一个图中绘制。我希望图例在框外。同时,我不想改变轴,因为图形的大小会变小。

我希望图例框位于绘图区域之外(我希望图例位于绘图区域的右侧)。有没有办法减小图例框内文本的字体大小,使图例框的大小变小?


当前回答

要将图例放置在绘图区域之外,请使用legend()的loc和bbox_To_anchor关键字。例如,以下代码将图例放置在绘图区域的右侧:

legend(loc="upper left", bbox_to_anchor=(1,1))

有关详细信息,请参阅图例指南

其他回答

这不完全是你所要求的,但我发现这是解决同样问题的一个替代方案。

使图例半透明,如下所示:

使用以下工具执行此操作:

fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label=label, color=color)
# Make the legend transparent:
ax.legend(loc=2, fontsize=10, fancybox=True).get_frame().set_alpha(0.5)
# Make a transparent text box
ax.text(0.02, 0.02, yourstring, verticalalignment='bottom',
                    horizontalalignment='left',
                    fontsize=10,
                    bbox={'facecolor':'white', 'alpha':0.6, 'pad':10},
                    transform=self.ax.transAxes)

当我有一个巨大的传奇时,对我有效的解决方案是使用额外的空图像布局。

在下面的示例中,我绘制了四行,在底部绘制了带有图例偏移的图像(bbox_to_anchor)。在顶部,它不会被切割。

f = plt.figure()
ax = f.add_subplot(414)
lgd = ax.legend(loc='upper left', bbox_to_anchor=(0, 4), mode="expand", borderaxespad=0.3)
ax.autoscale_view()
plt.savefig(fig_name, format='svg', dpi=1200, bbox_extra_artists=(lgd,), bbox_inches='tight')

我只使用字符串“左中”作为位置,就像在MATLAB中一样。

我从Matplotlib导入了pylab。

代码如下:

from matplotlib as plt
from matplotlib.font_manager import FontProperties

t = A[:, 0]
sensors = A[:, index_lst]

for i in range(sensors.shape[1]):
    plt.plot(t, sensors[:, i])

plt.xlabel('s')
plt.ylabel('°C')
lgd = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), fancybox = True, shadow = True)

只需在plot()调用之后调用legend(),如下所示:

# Matplotlib
plt.plot(...)
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

# Pandas
df.myCol.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))

结果如下:

简短回答:在图例上调用可拖动功能,并将其交互式移动到您想要的任何位置:

ax.legend().draggable()

长篇大论:如果您更喜欢交互式/手动放置图例,而不是以编程方式放置图例,则可以切换图例的可拖动模式,以便将其拖动到任何位置。检查以下示例:

import matplotlib.pylab as plt
import numpy as np
#define the figure and get an axes instance
fig = plt.figure()
ax = fig.add_subplot(111)
#plot the data
x = np.arange(-5, 6)
ax.plot(x, x*x, label='y = x^2')
ax.plot(x, x*x*x, label='y = x^3')
ax.legend().draggable()
plt.show()