Blitzkoder
Blitzkoder

Reputation: 1838

Setting global "legend.loc" for matplotlib using rcParams?

I have to plot quite a number of graphs and, for all of them, I need to tell legend to find the best position:

plt.legend(loc="best")

However, I think it is not a good idea to call this function for every different figure-generating piece of code.

Is it possible to set this at the start of the Python script using rcParams or rc? I tried these at the start but none worked:

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

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

Overall, is there an idiomatic way to set global matplotlib settings so I can reduce the amount of repeated figure configuration code?

Upvotes: 1

Views: 2296

Answers (1)

Mr. T
Mr. T

Reputation: 12410

It is unclear, why your command rcParams['legend.loc'] = "best" doesn't influence the following figures. As you can see, it works as expected in the following code:

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

Upvotes: 1

Related Questions