24

In pandas and seaborn, it is possible to temporarily change the display/plotting options by using the with keyword, which applies the specified setting only to the indented code, while leaving the global settings untouched:

print(pd.get_option("display.max_rows"))

with pd.option_context("display.max_rows",10):
    print(pd.get_option("display.max_rows"))

print(pd.get_option("display.max_rows"))

Out:

60
10
60

When I similarly try with mpl.rcdefaults(): or with mpl.rc('lines', linewidth=2, color='r'):, I receive AttributeError: __exit__.

Is there a way to temporarily change the rcParams in matplotlib, so that they only apply to a selected subset of the code, or do I have to keep switching back and forth manually?

2 Answers 2

30

Yes, using stylesheets.

See: https://matplotlib.org/stable/tutorials/introductory/customizing.html

e.g.:

# The default parameters in Matplotlib
with plt.style.context('classic'):
    plt.plot([1, 2, 3, 4])

# Similar to ggplot from R
with plt.style.context('ggplot'):
    plt.plot([1, 2, 3, 4])

You can easily define your own stylesheets and use

with plt.style.context('/path/to/stylesheet'):
    plt.plot([1, 2, 3, 4])

For single options, there is also plt.rc_context

with plt.rc_context({'lines.linewidth': 5}):
    plt.plot([1, 2, 3, 4])
Sign up to request clarification or add additional context in comments.

Comments

18

Yes, the matplotlib.rc_context function will do what you want:

import matplotlib as mpl
import matplotlib.pyplot as plt
with mpl.rc_context({"lines.linewidth": 2, "lines.color": "r"}):
    plt.plot([0, 1])

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.