如何更新matplotlib hexbin绘图?

2024-09-30 20:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个matplotlibhexbin嵌入在一个GTK.Window中,它用图形表示一些数据(x,y)。我希望plot在收到新数据时更新(通过UDP)。不过,我有点麻烦。在

我可以用几种不同的方法使它工作,但是没有一种方法是“有效的”(意思是-重新绘制plot需要太长时间)。我看了看here并试图根据建议的答案对我的hexbin进行建模,但根本无法使其工作。我一直收到以下错误:

TypeError: 'PolyCollection' object is not iterable.

我猜hexbins不能以与标准plots相同的方式更新。在

示例代码:

class graph:
    def __init__(self):
        self.window = gtk.Window()
        self.figure = plt.figure()
        self.ax = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)
        self.window.add(self.canvas)

        self.graph = None

    def plot(self, xData, yData):
        if len(xData) > 1 and len(yData) > 1:
            self.graph, = self.ax.hexbin(self.xData, self.yData) 
            ###############################################
            ####This is where the code throws the error####

    def update(self, xData, yData):
        self.graph.set_xdata(np.append(self.graph.get_xdata(), xData))
        self.graph.set_ydata(np.append(self.graph.get_ydata(), yData))
        self.figure.canvas.draw()

代码的用法如下:

^{pr2}$

这只是我如何使用代码的一个很小的例子。我对matplotlib没有太多的经验,所以我有可能把这件事完全弄错了。(这很可能是我在做的)

所以我的终极问题是-如何更新matplotlibhexbin图?


编辑:多亏了danodonovan的回答,我修改了我的代码并删除了^{之后的','

引发的新错误是:AttributeError: 'PolyCollection' object has no attribute 'set_xdata'


Tags: 数据方法代码selfplotdefwindowgraph
3条回答

我认为目前还不能做到,hexbin转换x,y->;多边形集合的列表。polyCollection只是垂直、边缘和脸部颜色的列表,我不认为它包含任何关于它是如何生成的语义信息。在

最好的方法是用核弹摧毁旧的hexbin,然后用一个新的来代替它。在

如果您真的希望能够就地更新,要么使用一个正方形的2d直方图(这样您就可以使用imshow),要么修改{}以返回补丁列表(而不是polyCollection),并跟踪自己的分块情况。在

行:

 self.graph, = self.ax.hexbin(self.xData, self.yData)

(如果这是堆栈跟踪抛出异常的地方)可能是因为逗号,这意味着self.ax.hexbin是一个iterable对象。换成

^{pr2}$

可能会停止TypeError exception。下一次,在堆栈跟踪中提供更多的行-这可能有助于澄清问题。在

要回答您预期的问题,请不要调用set_xdata尝试类似update_from的方法。我不保证这会奏效,但我会努力的

def update(self, xData, yData):
    # update your data structures
    self.xData = np.append(self.xData, xData)
    self.yData = np.append(self.yData, yData)

    # create a new hexbin - not connected to anything, with the new data
    new_hexbin = self.ax.hexbin(self.xData, self.yData)

    # update the viewed hexbin from the new one
    self.graph.update_from(new_hexbin)
    self.figure.canvas.draw()

请注意,没有更多的代码或解释,这真的只是猜测工作!这个类的文档是here^{}方法来自parent class。在

相关问题 更多 >