【问题标题】:Clear figure subplots matplotlib python清除图形子图 matplotlib python
【发布时间】:2017-06-20 01:51:42
【问题描述】:

我写了一个简单的 Python 函数来生成一个 matplotlib 图形。我从一个单独的脚本中多次调用plotData,但每次它都会生成一个新的情节。我想要的是始终只有一个带有 subplot.clear() 之类的图来清除数据更改之间的子图。

我需要一种从外部plotData 识别图形的方法,以便我可以清除绘图以获取新数据。实现这一目标的最佳方法是什么?

## Plot Data Function
def plotData(self):

        # Setup figure to hold subplots
        f = Figure(figsize=(10,8), dpi=100)

        # Setup subplots
        subplot1=f.add_subplot(2,1,1)
        subplot2=f.add_subplot(2,1,2)

        # Show plots
        dataPlot = FigureCanvasTkAgg(f, master=app)
        dataPlot.show()
        dataPlot.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)

【问题讨论】:

    标签: python matplotlib tkinter


    【解决方案1】:

    我不确定我是否完全理解问题所在。 如果要更新绘图,则需要执行此操作的函数。我会将此函数称为plotData。在此之前,您还需要设置情节。这就是您目前在plotData 中拥有的内容。所以让我们把它重命名为generatePlot。

    class SomeClass():
        ...
    
        def generatePlot(self):
            # Setup figure to hold subplots
            f = Figure(figsize=(10,8), dpi=100)
    
            # Setup subplots
            self.subplot1=f.add_subplot(2,1,1)
            self.subplot2=f.add_subplot(2,1,2)
    
            # Show plots
            dataPlot = FigureCanvasTkAgg(f, master=app)
            dataPlot.show()
            dataPlot.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)
    
        ## Plot Data Function
        def plotData(self, data, otherdata):
            #clear subplots
            self.subplot1.cla()
            self.subplot2.cla()
            #plot new data to the same axes
            self.subplot1.plot(data)
            self.subplot2.plot(otherdata)
    

    现在您只需在开始时调用一次generatePlot。之后,您可以随时使用新数据更新绘图。

    【讨论】:

      【解决方案2】:

      你可以使用

      subplot.cla()  # which clears data but not axes
      subplot.clf()  #  which clears data and axes
      

      【讨论】:

      • 另外,如果您将图形和子图定义为 self.fig 和 self.subplots 等。那么您可以从它们所属的类实例中访问它们。
      • 如果定义了self ,您将如何搜索图形?在应用修改代码之前,它必须以某种方式重新定位。
      • 今天命令 subplot.clf() 被 subplot.clear() 替换。
      猜你喜欢
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 2017-08-17
      • 2019-10-04
      • 2018-01-30
      相关资源
      最近更新 更多