martina martina - 3 months ago 35
Python Question

Matplotlib figure size in Jupyter reset by inlining in Jupyter

This question is more of a curiosity.

To change the default fig size to a custom one in matplotlib, one does

from matplotlib import rcParams
from matplotlib import pyplot as plt
rcParams['figure.figsize'] = 15, 9


after that, figure appears with chosen size.

Now, I'm finding something new (never happened/noticed before just now): in a Jupyter notebook, when inlining matplotlib as

%matplotlib inline


this apparently overwrites the
rcParams
dictionary restoring the default value for the figure size. Hence in oder to be able to set the size, I have to inline
matplotlib
before changing the values of the
rcParams
dictionary.

I am on a Mac OS 10.11.6, matplotlib version 1.5.1, Python 2.7.10, Jupyter 4.1.

Answer

IPython's inline backend sets some rcParams when it is initialized. This is configurable, and you can override it with your own configuration:

# in ~/.ipython/ipython_config.py
c.InlineBackend.rc = {
    'figure.figsize': (15, 9)
}

The above would replace all of the rcParams that the inline backend sets, and you get total control. If you already have a matplotlib style that works nicely for inline output, you can tell the backend to leave everything alone:

c.InlineBackend.rc = {}

If you want to change just a few values, rather than overriding the whole thing, you can use the dictionary .update method:

c.InlineBackend.rc.update({'figure.figsize': (15, 9)})

In the future, the inline backend should be doing its defaults via matplotlib's nice new style mechanism, which should make it behave nicer in terms of respecting your preferences and allowing easier customization.