Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to understand how to use "set_ydata" method, I found many examples on matplotlib webpages but I found only codes in which "set_ydata" is "drowned" in large and difficult to understand codes.

I would like a short and easy to understand code that help me understanding how "set_ydata" works. Here a short code that provide the plot underneath

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3, 3, 0.01)
j = 1
y = np.sin( np.pi*x*j ) / ( np.pi*x*j )
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y)
plt.show()

Now, with the following code, I delete the line drawn on the "ax" subplot, I use "set_ydata" to modify the plot and finally I would like to draw the line again, but I don't find anything that do the last step

line.remove()
j = 2
y = np.sin( np.pi*x*j ) / ( np.pi*x*j )
line.set_ydata(y)

It is not surprising that you see nothing if you remove the line that you set the data to.

As the name of the function set_data suggests, it sets the data points of a Line2D object. set_ydata is a special case which does only set the ydata.

The use of set_data mostly makes sense when updating a plot, as in your example (just without removing the line).

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3, 3, 0.01)
j = 1
y = np.sin( np.pi*x*j ) / ( np.pi*x*j )
fig = plt.figure()
ax = fig.add_subplot(111)
#plot a line along points x,y
line, = ax.plot(x, y)
#update data
j = 2
y2 = np.sin( np.pi*x*j ) / ( np.pi*x*j )
#update the line with the new data
line.set_ydata(y2)
plt.show()

It is obvious that it would have been much easier to directly plot ax.plot(x, y2). Therefore set_data is commonly only used in cases where it makes sense and to which you refer as "large and difficult to understand codes".

There where two issues with my code. The first is what you are saying: "line.remove()" delete the plot and you want draw it anymore! The second is that I am using jupyter notebook and I have to add the line "%matplotlib notebook" at the begining of the script otherwise I can't change the plot once it is done. – Stefano Fedele Dec 18, 2016 at 16:21

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.