Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
joelostblom Avatar asked Feb 14 '16 17:02

joelostblom


People also ask

What does rcParams do in python?

Changing the Defaults: rcParams Each time Matplotlib loads, it defines a runtime configuration (rc) containing the default styles for every plot element you create. This configuration can be adjusted at any time using the plt. rc convenience routine.

What is interactive mode Matplotlib?

Matplotlib can be used in an interactive or non-interactive modes. In the interactive mode, the graph display gets updated after each statement. In the non-interactive mode, the graph does not get displayed until explicitly asked to do so.

How do you change styles in Matplotlib?

Another way to change the visual appearance of plots is to set the rcParams in a so-called style sheet and import that style sheet with matplotlib. style. use . In this way you can switch easily between different styles by simply changing the imported style sheet.

Which of the following function is used to locate the Matplotlib config directory?

config/matplotlib/matplotlibrc . The rc configuration file is found under $INSTALL_DIR/matplotlib/mpl-data/matplotlibrc , where $INSTALL_DIR is where you installed Matplotlib, ...


2 Answers

Yes, using stylesheets.

See: http://matplotlib.org/users/style_sheets.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])
like image 191
MaxNoe Avatar answered Nov 02 '22 06:11

MaxNoe


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])
like image 32
mwaskom Avatar answered Nov 02 '22 05:11

mwaskom