简体   繁体   中英

Matplotlib is not recognizing the attribute set_xdata.

In reference to this post : I have been attempting to run the following code for plotting and live updating a graph. However, I am welcomed by the following error every time I attempt to run the function: AttributeError: 'list' object has no attribute 'set_xdata'

The rest of the function looks like the following:

def getData(self):
    self.data = random.gauss(10,0.1)
    self.ValueTotal.append(self.data)
    #With value total being a list instantiated as ValueTotal = []
    self.updateData()

def updateData(self):

    if not hasattr(self, 'line'):
        # this should only be executed on the first call to updateData
        self.widget.canvas.ax.clear()
        self.widget.canvas.ax.hold(True)
        self.line = self.widget.canvas.ax.plot(self.ValueTotal,'r-')
        self.widget.canvas.ax.grid()
    else:
        # now we only modify the plotted line
        self.line.set_xdata(np.arange(len(self.ValueTotal)))
        self.line.set_ydata(self.ValueTotal)

    self.widget.canvas.draw()   

While this code originated from sebastian and Jake French I have not had any success implementing this.Is there something I am doing wrong? What generates this error and how can I fix?

This is used strictly for an example and will not be copied into my code. I am simply using it for referential material and felt this would be the simplest way to communicate my problems with the community. I take no credit for the previous code.

As Joe Kington pointed out: plot returns a list of artists of which you want the first element:

self.line = self.widget.canvas.ax.plot(self.ValueTotal,'r-')[0]

So, taking the first list element, which is the actual line.

A minimal example to replicate this behavior:

l = plt.plot(range(3))[0]
l.set_xdata(range(3, 6))

l = plt.plot(range(3))
l.set_xdata(range(3, 6))

The first one runs fine and the second one gives the AttributeError.

The idiom to do that is:

x = np.arange(0,10,0.1)
l, = plt.plot(x,x*x)
l.set_xdata(range(3, 6))

It takes the first element of Line2D list, which allows to manipulate the whole list of coordinates using set_xdata() and set_ydata() .

Note that this does not work:

x = np.arange(0,10,0.1)
l,_ = plt.plot(x,x*x)
l.set_xdata(range(3, 6))

(Seeing the idiom with line, = in many code examples I used to think that plot() returns a pair of values, which is not true).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM