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)
not "plt.draw()" neither "plt.show()" draw anything. Could you suggest me anything that draw the new line?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With