Matplotlib - How is rc_context() used?

Apostolos Source

In matplotlib documentation, at https://matplotlib.org/api/matplotlib_configuration_api.html, the following "pseudo example" is provided, followed by a short "pseudo explanation":

with mpl.rc_context(fname='screen.rc'):
  plt.plot(x, a)
  with mpl.rc_context(fname='print.rc'):
    plt.plot(x, b)
  plt.plot(x, c)

The 'a' vs 'x' and 'c' vs 'x' plots would have settings from 'screen.rc', while the 'b' vs 'x' plot would have settings from 'print.rc'.


For me, this is an "equation with 5 unknowns": 'screen.rc', 'print.rc', 'a', 'b' and 'c'. More specifically: 1) what are the files 'screen.rc' 'print.rc' and where are they found or how are they created? and 2) what do the variables 'a', 'b' and 'c' represent and how are they set?

It seems that this "example" is quite famous, since I have found an exact copy of it, including the short description, in a dozen of different places. What is most interesting is that no one, not even the matplotlib staff itself, cared to explain how can this stuff be actually applied.

Is there someone who has concrete information about this example or can one give a concrete example of how is rc_context() used?

pythonmatplotlib

Answers

answered 1 week ago ImportanceOfBeingErnest #1

The example you show comes from the documentation of the respective method. Such methods have little space to go into much detail, so please don't blame the people for actually providing such example in the unusual place of a method docstring.

A more detailed explanation of the rc file, the context and examples are found in the Customizing tutorial (the second tutorial in the tutorials page, little chance to miss it).

Sticking to the case from the question, the concrete case is you have a python file which contains this code, and in addition you have two text files, named screen.rc and print.rc.

The .py file:

import matplotlib as mpl
import matplotlib.pyplot as plt

x = [1,2,3,4]
a = [1,2,4,4]
b = [1,1,2,4]
c = [2,3,3,1]


with mpl.rc_context(fname='screen.rc'):
  plt.plot(x, a)
  with mpl.rc_context(fname='print.rc'):
    plt.plot(x, b)
  plt.plot(x, c)

plt.show()

The screen.rc file:

lines.linewidth   : 1       ## line width in points
lines.linestyle   : -       ## linestyle 

The print.rc file:

lines.linewidth   : 5       ## line width in points
lines.linestyle   : :       ## linestyle 

Running the py file would produce something like this as output

enter image description here

The blue line is the one created from plt.plot(x, a). It has a solid linestyle and is one point wide. Similar, the green line, plt.plot(x, c), because both are inside the screen.rc context, but not within the print.rc. The orange line is the one created from within the print.rc context. It hence has a linewith of 5 points and is dotted.

comments powered by Disqus