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

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


当前回答

你也可以试试figlegend。可以创建独立于任何Axes对象的图例。但是,您可能需要创建一些“虚拟”路径,以确保正确传递对象的格式。

其他回答

要将图例放置在绘图区域之外,请使用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)

我只使用字符串“左中”作为位置,就像在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)

这里有一个matplotlib教程的示例。这是一个更简单的示例,但我为图例添加了透明度,并添加了plt.show(),这样您就可以将其粘贴到交互式shell中并获得结果:

import matplotlib.pyplot as plt
p1, = plt.plot([1, 2, 3])
p2, = plt.plot([3, 2, 1])
p3, = plt.plot([2, 3, 1])
plt.legend([p2, p1, p3], ["line 1", "line 2", "line 3"]).get_frame().set_alpha(0.5)
plt.show()

通过指定FontProperties的set_size,可以使图例文本变小。资源:图例指南matplotlib.legendmatplotlib.pyplot.legend字体管理器set_size(自身,大小)有效字体大小为xx小、x小、小、中、大、x大、xx大、大、小和无。Real Python:使用Matplotlib绘制Python(指南)

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

fontP = FontProperties()
fontP.set_size('xx-small')

p1, = plt.plot([1, 2, 3], label='Line 1')
p2, = plt.plot([3, 2, 1], label='Line 2')
plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)

fontsize='xx-small'也可以工作,无需导入FontProperties。

plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')