【问题标题】:Why are these functions not drawing on the same graph together?为什么这些函数没有一起绘制在同一张图上?
【发布时间】:2016-12-02 04:09:00
【问题描述】:

我希望能够单击在 IPython GUI 中生成的两个按钮,然后在同一张图上生成总共 6 个点。但是,现在单击这两个按钮不会创建 6 个点,而只会创建由要单击的第一个按钮创建的图形。我做错了什么?

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from ipywidgets.widgets import Button
from IPython.display import display

class Test(object):
    def __init__(self):
        self.figure = plt.figure()
        self.ax = self.figure.gca()
        self.button = Button(description = "Draw new points.")
        display(self.button)
        self.button.on_click(self.button_clicked)
        self.button2 = Button(description = "Draw more points.")
        display(self.button2)
        self.button2.on_click(self.button_clicked2)

    def button_clicked(self, event):
        self.ax.scatter([1,2,8], [6,5,4])
        self.figure.canvas.draw()
        plt.show()

    def button_clicked2(self, event):
        self.ax.scatter([1,0,5], [3,8,3])
        self.figure.canvas.draw()
        plt.show()

test = Test()

【问题讨论】:

    标签: python matplotlib ipython


    【解决方案1】:

    我玩弄了您的代码,并通过添加 %matplotlib notebook 并删除对 plt.show() 的调用来使其工作。

    %matplotlib notebook
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    from ipywidgets.widgets import Button
    from IPython.display import display
    
    class Test(object):
        def __init__(self):
            plt.ion()
            self.figure = plt.figure()
            self.ax = self.figure.gca()
            self.button = Button(description = "Draw new points.")
            display(self.button)
            self.button.on_click(self.button_clicked)
            self.button2 = Button(description = "Draw more points.")
            display(self.button2)
            self.button2.on_click(self.button_clicked2)
    
        def button_clicked(self, event):
            self.ax.scatter([1,2,8], [6,5,4])
            self.figure.canvas.draw()
    
        def button_clicked2(self, event):
            self.ax.scatter([1,0,5], [3,8,3])
            self.figure.canvas.draw()
    
    test = Test()
    

    确保您安装了最新版本的 matplotlib。此功能取决于 nbagg 后端。请参阅this question 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      相关资源
      最近更新 更多