2

I have a problem with Matplotlib 1.0.1

I create a figure, and the I use an onclick event to do stuff when I click into the figure. One thing is, that it has to create a new figure with new data in it. This perfectly works in Matplotlib 0.99.3, where I developed the script, but now a collegue tried it on his machine, which has matplotlib 1.0.1 (and python 2.6 instead of 2.7), and the figure is not shown.

However, I think the figure is created, but not shown, because if I close the first figure, the script is not ended, it is still running.

Here is a simple example code:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

a = [1,2,3]
b = [4,2,9]

line = ax.plot(a,b)

def onclick(event):
    print "clicked"
    a = [7,8,9]
    b = [1,9,20]
    fig2 = plt.figure()
    ax_single = fig2.add_subplot(111)
    line2 = ax_single.plot(a,b)

cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()

Is this a (known) bug in matplotlib 1.0.1? Is there any way around it?

Thx.

Pythoneer
  • 165
  • 1
  • 12

2 Answers2

2

Adding a simple fig2.show() did the trick to me. Read the How-to to get more information!

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

a = [1,2,3]
b = [4,2,9]

line = ax.plot(a,b)

def onclick(event):
    print "clicked"
    a = [7,8,9]
    b = [1,9,20]
    fig2 = plt.figure()
    ax_single = fig2.add_subplot(111)
    line2 = ax_single.plot(a,b)
    fig2.show()

cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()

The was indeed a change in 1.0.0 in the way matplotlib handles figures after the mainloop has been started.

David Zwicker
  • 23,581
  • 6
  • 62
  • 77
  • +1: This is essentially the (new) documented behavior of `pyplot.show()`: it displays figures that were updated/created since the last `show()`. Reference: http://matplotlib.sourceforge.net/users/whats_new.html#multiple-calls-to-show-supported. – Eric O. Lebigot Feb 24 '12 at 13:20
0

You can put Pyplot in interactive mode at the beginning:

plt.ion()

and then end your program with something like

raw_input('Press enter when done...')

(instead of show()).

The semantics of show() and of the interactive mode were updated with Matplotlib 1.0. You can get more information on this on StackOverflow: Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?. I understand that using the interactive mode (ion) is generally more convenient. Another important point is that in interactive mode, only pyplot.* functions automatically draw/redraw plots (and not <object>.*() methods).

Community
  • 1
  • 1
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260