John Smith
John Smith

Reputation: 1233

how to set local rcParams or rcParams for one figure in matplotlib

I am writing a plotting function in python using matplotlib. The user can specify some things, e.g. "tick lines". The easiest way would be to change the rcParams, but those are global properties, so all new plots will have tick lines after that plotting function was called.

Is there a way to set the plotting defaults specifically for just one figure?

Or is there at least a good way to change the properties for one plotting-function and then change them back to the values that were used before (not necessarily the rcdefaults)?

Upvotes: 13

Views: 6340

Answers (1)

mwaskom
mwaskom

Reputation: 49002

You can use the rc_context function in a with statement, which will set the rc parameters with a dictionary you provide for the block indented below and then reset them to whatever they were before after the block. For example:

with plt.rc_context({"axes.grid": True, "grid.linewidth": 0.75}):
    f, ax = plt.subplots()  # Will make a figure with a grid
    ax.plot(x, y)

f, ax = plt.subplots()  # Will make a figure without a grid
ax.plot(x, y)

Upvotes: 26

Related Questions