【问题标题】:Python/Matplotlib 1.0.1 does not open new figure when clickedPython/Matplotlib 1.0.1 单击时不打开新图
【发布时间】:2012-02-24 20:44:31
【问题描述】:

我对 Matplotlib 1.0.1 有疑问

我创建了一个图形,当我单击该图形时,我使用 onclick 事件来做一些事情。一件事是,它必须创建一个包含新数据的新图形。这在我开发脚本的 Matplotlib 0.99.3 中完美运行,但现在一位同事在他的机器上尝试了它,它有 matplotlib 1.0.1(和 python 2.6 而不是 2.7),并且没有显示该图。

但是,我认为该图已创建,但未显示,因为如果我关闭第一个图,则脚本并未结束,它仍在运行。

这是一个简单的示例代码:

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()

这是 matplotlib 1.0.1 中的(已知)错误吗?有什么办法解决吗?

谢谢。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    添加一个简单的 fig2.show() 对我有用。阅读How-to以获取更多信息!

    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()
    

    在主循环启动后,matplotlib 处理数字的方式确实是 1.0.0 的变化。

    【讨论】:

    【解决方案2】:

    您可以在开始时将 Pyplot 置于交互模式:

    plt.ion()
    

    然后用类似的东西结束你的程序

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

    (而不是show())。

    show() 和交互模式的语义已使用 Matplotlib 1.0 进行了更新。您可以在 StackOverflow 上获得更多信息:Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?。我知道使用交互模式(ion)通常更方便。另一个重要的一点是,在交互模式下,只有pyplot.* 函数会自动绘制/重绘绘图(而不是<object>.*() 方法)。

    【讨论】:

      猜你喜欢
      • 2017-03-18
      • 2021-08-27
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-08
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多