I'm currently learning the basic philosophy of making plots with matplotlib
in Python with Jupyter Notebook. My main gripe is when it comes to creating subplots, why do I have to run the code in one single chunk? And whenever I try to run it in separate steps, it throws me weird plots. For exampple:
plt.subplot(211)
plt.plot(range(10))
plt.subplot(212, facecolor='y')
plt.plot(randn(50))
I have to excute those four lines of codes in one step as opposed to run them each in four steps. What's exactly going on here? Why is there such a difference between the two approaches?
1 Answer 1
In a jupyter notebook, once a cell is evaluated and the figure is shown you're loosing the reference to it and the figure produced in that cell is closed.
In the new cell, when calling plt.subplot()
, pyplot does not see any open figure, so it creates a new one.
Most pyplot commands work like this: Find out if there is an open figure (possibly a current axes as well). If this is the case, operate on that figure (axes), if not, create it. This is why it's often called statemachine; depending on the current state, do something.
Opposed to that there is also an object oriented API. It works by explicitely calling the methods of the objects you want to operate on. So in order to reuse the figures or axes from previous cells, we would keep a reference to them.
Explicitely call fig = plt.figure()
, such that fig
is still available in the next cell. Same with axes, call ax = fig.add_subplot(111)
to have the subplot available in the next cell. At any point, call fig
to invoke the display of the figure.
Here is an example:
-
Thank you a lot. This is exactly what I'm looking for. The 'memoryless' thing doesn't seem very intuitive to me at all though.James Wong– James Wong2017年04月01日 11:42:47 +00:00Commented Apr 1, 2017 at 11:42
Explore related questions
See similar questions with these tags.
plt.subplots()
(with an "s"). This approach is a little different from the classical matlab style and allows you to declare the figure and a tuple of axes in a single line, e.g.fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
. These axes can be assigned new data at any time.plt.subplot
or usingplt.subplots
. The point is whether to use the statemachine or the oo api, i.e. whether to keep a reference to the object or not.add_subplots
does not modify any position. It just adds a subplot at a given position on the grid. Anyways I think the main point got across: You can do what ever you like in any cell you like, as long as you keep track of you object handles.