设置全局" legend.loc"对于matplotlib使用rcParams?

时间:2018-05-19 23:53:20

标签: python matplotlib

我必须绘制相当多的图表,对于所有图表,我需要告诉legend找到最佳位置:

plt.legend(loc="best")

但是,我认为为每个生成代码的代码调用此函数并不是一个好主意。

是否可以使用rcParamsrc在Python脚本的开头设置此项? 我在开始时尝试过这些但没有效果:

rcParams['legend.loc'] = "best"

rc('legend', loc="best")

总的来说,是否存在设置全局matplotlib设置的惯用方法,以便减少重复图形配置代码的数量?

1 个答案:

答案 0 :(得分:1)

目前尚不清楚,为什么你的命令rcParams['legend.loc'] = "best"不会影响以下数字。如您所见,它在以下代码中按预期工作:

import numpy as np
from matplotlib import pyplot as plt

#possible legend locations
leg_loc = {0: "best",
           1: "upper right",
           2: "upper left",
           3: "lower left",
           4: "lower right",
           5: "right",
           6: "center left",
           7: "center right",
           8: "lower center",
           9: "upper center",
           10: "center"}

#random legend location
loc_num = np.random.randint(10)
#set it for all following figures
plt.rcParams['legend.loc'] = leg_loc[loc_num]

#create three figures with random data
n = 10
xdata = np.arange(n)

for i in range(3):
    plt.figure(i)
    ydata = np.random.random(n)
    #set some points in right upper corner, in case legend location is "best"
    if i == 1:
        ydata[-3:] = 0.98
    plt.scatter(xdata, ydata, label = "data #{}\nlegend location: {}".format(i, leg_loc[loc_num]))
    plt.legend()

plt.show()