Get a reference to a figure created in a different scope

I’ve created a Python package that creates a variety a plots in a non-sequential manner. That is, some data is generated and then added to a plot, and then more data is generated and added to the same plot, and then another batch of data is generated and it’s added to a new plot. I initially created this with matplotlib, and this paradigm works because mpl has the concept of a “current figure” that can be set by the user. Is there any equivalent or similar method with Plotly?

I’m aware of add_traces, but to use that I’d need to always retain a reference to the figure. Unfortunately, by using the matplotlib paradigm, I committed to not retaining references to the figures that are created.

Hey @rafmudaf welcome to the forums.

I guess current figure in this context in mpl means last opened one?

Hi @AIMPED thanks for the response. Here’s a small example of the use case I’m describing in mpl:

def plot_line(x, y):
    ax = plt.gca()                  # <-- This is the crux
    ax.plot(x, y)

x = x_axis_data()

fig, ax1 = plt.subplots()           # ax1 is the current axis
plot_line(x, some_data())

fig, ax2 = plt.subplots()
plot_line(x, some_other_data())     # ax2 is the current axis

plt.axes(ax1)                       # Makes ax1 the current axis again
plot_line(x, some_other_additional_data())

plt.show()

In many cases, it will be that the most recently opened plot is the current figure, but in this case I’m using matplotlib to build plots over a series of events and then present them at the end of the events. Matplotlib provides a method to make a particular plot (actually, it’s the axis) the current one.

In case it helps, here’s my Python package: GitHub - rafmudaf/wcomp. The line that get’s the current axis is here, and this is used in the Jupyter Notebooks here and here.

Hi @rafmudaf.

Frankly I don’t see a big difference here :hugs:. In mpl you pass around the axes to add stuff to the figure.

In plotly you just would pass the figure object you want to add to.

But maybe I’m not getting the point with mlp and there is a hidden [built in] mechanism which keeps track somehow of the current axis or figure.

Anyways, in plotly you need to know, to which figure you want to add to and use fig.add_trace() :upside_down_face: