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

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


当前回答

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

其他回答

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

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

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()

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

除了这里的所有优秀答案之外,如果可能的话,matplotlib和pylab的更新版本可以自动确定将图例放置在何处,而不干扰绘图。

pylab.legend(loc='best')

如果可能,这将自动将图例远离数据!

然而,如果没有任何地方可以在不重叠数据的情况下放置图例,那么您需要尝试其他答案之一;使用loc=“best”永远不会将图例置于情节之外。

更新版本的Matplotlib使图例更容易定位在绘图之外。我使用Matplotlib版本3.1.1生成了这个示例。

用户可以向loc参数传递2元组坐标,以将图例定位在边界框中的任何位置。唯一的问题是,您需要运行plt.tight_layout()来获取matplotlib以重新计算绘图尺寸,以便图例可见:

import matplotlib.pyplot as plt

plt.plot([0, 1], [0, 1], label="Label 1")
plt.plot([0, 1], [0, 2], label='Label 2')

plt.legend(loc=(1.05, 0.5))
plt.tight_layout()

这导致以下绘图:

参考文献:

matplotlib.pyplot.legend