Search code examples
pythonpandasmatplotlibseaborn

Is there a context manager for temporarily changing matplotlib settings?


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?


Solution

  • 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])