python - 如何查看 matplotlib 旁边的图例?

标签 python matplotlib

我在 matplotlib 中有一个绘图,其中有很多行。我有一个相当广泛的图例,我使用以下代码将它放在我的情节旁边:

fontP = FontProperties()
fontP.set_size('small')
plt.legend(variablelist, loc=0, prop = fontP, bbox_to_anchor=(1.0, 1.0))
plt.savefig(filename+'.png')

结果如下: enter image description here

然而,如您所见,图例在右侧被截断了。有没有一种方法可以在图像的右侧创建更多空间,以便我可以看到完整的图例?

欢迎所有提示!

为了回应@mmgp,我在下面发布了以下代码。正如您从他的回答中看到的那样,我忘记将 bbox_inches='tight' 添加到 savefig 部分。因此,为了让 future 的读者拥有一个完整的工作代码,我只是在下面的代码中添加了 bbox_inches='tight',这使得它工作得非常好.. :) :

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

mylist = []
for a in range(10):
    mylist.append([])
    for b in range(10):
        mylist[a].append(random())
        
x = range(len(mylist))
for enum, i in enumerate(mylist):
    plt.plot(x, mylist[enum], label='label_'+str(enum))

plt.grid(b=True)
fontP = FontProperties()
fontP.set_size('small')

variablesList = []
for i in range(10):
    variablesList.append('label_'+str(i))

legenda = plt.legend(variablesList, loc=0, prop = fontP, bbox_to_anchor=(1.0, 1.0))
plt.savefig('testplot.png', bbox_extra_artists=[legenda], bbox_inches='tight')

最佳答案

现在差不多了,只需在 savefig 中添加一个新参数:bbox_inches = 'tight'。这使得 matplotlib 计算出您的绘图所需的大小。

关于python - 如何查看 matplotlib 旁边的图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13787275/

相关文章:

python - df_dates = df.loc[ :, "Date"] 无法读取 'Date' 列(数据来自 yahoo Fin)

python - 在分隔符处加入 python 列表

python - matplotlib matshow : How to change each row height based on a scaling vector?

python - 将容器添加到 python 中预先存在的对象的简单但正确的方法是什么?

python - 使用 curve_fit 获取 r 平方值

python - self.locals SyntaxError : Missing parentheses in call to 'exec' 中的 pytest 执行代码

python - 使用python 3从网页抓取数据,需要先登录

python - 如何在没有重复的情况下找到两个数组中最接近的元素 [duplicates] 并在 Python 中返回两个数组的索引?

python - 阻止 pyplot.contour 沿不连续点绘制轮廓

python - 如何拆分y轴标签并分别为每个部分着色?