-
-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Description
Problem
pyplot.plot will only create a new figure if there are no active figures. Thus when I am in a jupyter notebook with the ipympl backend I often write the following snippet:
plt.figure()
plt.plot(...)There are two issues, one of convenience and one of user confusion:
- I'd prefer to not have to write
plt.figureevery time I want a new figure to show up. - The current situation can be confusing to new users see %matplotlib ipympl does not allow cell "re-plot" ? ipympl#248
- In particular this breaks the expectation established by usage of the inline backend that
plt.plotin a cell will always create a new figure
- In particular this breaks the expectation established by usage of the inline backend that
My examples are both jupyter centric as that is my primary environment, but it feels as though the proposed solutions would belong in matplotlib proper rather than a backend.
Proposed Solution
Create two new functions in pyplot: plot_figure and plot_subplots that are guaranteed to create a new figure and otherwise act like pyplot.plot. Below are two incomplete implementations that I have been using.
def plot_figure(*args, **kwargs):
"""
Calls plt.figure() for you, and then acts like plt.plot
"""
if 'figsize' in kwargs:
fig = figure(kwargs['figsize'])
del kwargs['figsize']
else:
fig = figure()
lines = plt.plot(*args, **kwargs)
return fig, lines
def plot_subplots(*args, **kwargs):
"""
Calls plt.subplots() for you, and then acts like plt.plot
"""
if 'figsize' in kwargs:
fig, ax = plt.subplots(figsize=kwargs['figsize'])
del kwargs['figsize']
else:
fig, ax = plt.subplots()
lines = plt.plot(*args, **kwargs)
return fig, ax, linesAdditional context and prior art
Something that would be nice but probably is not technically feasible is a matplotlib figure that is associated with a specific juptyer cell. The proposed solution approximates such a figure per cell behavior. I think this desire is residual from my having "grown up" as it were using the inline backend. There are now features that I want from the interactive backend, but old habits like expecting plt.plot to just create a figure die hard.