Skip to content

Create a sibling to pyplot.plot that garuntees the creation of a new figure #18248

@ianhi

Description

@ianhi

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:

  1. I'd prefer to not have to write plt.figure every time I want a new figure to show up.
  2. 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.plot in a cell will always create a new figure

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, lines

Additional 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions