Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plotting subplots to existing figure

I'm wondering if there's an equivalent function to

fig, axarr = plt.subplots(3, 2, sharex='col', sharey='row')

where only the axes array is generated for an existing figure, instead of creating a new figure object. I basically need to create a matplotlib window, populate it, and update it when a button has been pressed. I would like to use the subplots method as it allows sharing axes, but it forces the creation of a new figure object, which would open a new window.

My current code looks like this:

fig = plt.figure()

# When button is pressed
fig.clear()
for i in range(6):
    ax = fig.add_subplot(3, 2, i+1)
    ax.plot(x, y)
plt.draw()

And I'd like to do something like

fig, axarr = plt.subplots(3, 2, sharex='col', sharey='row')

# When button is pressed
fig.clear()
axarr = fig.subplots(3, 2, sharex='col', sharey='row')
for i in range(3):
    for j in range(2):
        ax = axarr[i][j]
        ax.plot(x, y)
plt.draw()

Alternatively, is there a way to directly work with the matplotlib windows? I could plot the new figure object into the existing window if that is an option as well.

I am using the PySide backend if that makes any difference. Thanks.

like image 940
Neo Avatar asked Jul 06 '16 18:07

Neo


People also ask

Which function adds a subplot to the current figure?

subplot() function adds subplot to a current figure at the specified grid position.


2 Answers

A dirty workaround:

you can use the keyword num to specify the figure handle explicitly:

import matplotlib.pyplot as plt
fig1, axes1 = plt.subplots(5, 4, gridspec_kw={'top': 0.5}, num=1)
fig2, axes2 = plt.subplots(5, 4, gridspec_kw={'bottom': 0.5}, num=1)
plt.show()

This gives:

In [2]: fig1 is fig2
Out[2]: True

In [3]: axes1 is axes2
Out[3]: False

All subplot parameters have to be given to the grispec_kw and subplot_kw arguments in the beginning. They can't be change easily afterwards anymore.

like image 122
Matthias123 Avatar answered Oct 22 '22 19:10

Matthias123


This feature is implemented on the master branch via PR#5146 which is targetted for mpl 2.1 which should be out in the fall.

If you need it now either run the master branch or vendor that method as a function

axarr = vendored_subplots(fig, ...)
like image 1
tacaswell Avatar answered Oct 22 '22 20:10

tacaswell