'Python single plot in a for loop without creating a list or array
This may sound like a very naive question. However, to me, it's quite fundamental: Can python plot variables without putting them into arrays or lists? I couldn't find much answer on the net or SO and please let me know if there's any duplicate.
I have the following code for demonstration:
import matplotlib.pyplot as plt
import numpy as np
x = 0.0
dx = 0.5
for i in range(10):
y = x**2
plt.plot(x,y)
x += dx
plt.show()
x = np.linspace(-0,.5,10)
y = x**2
plt.plot(x,y)
plt.show()
The first part doesn't plot (which is in an explicit for-loop) anything while the second part does (where both x
and y
are numpy arrays).
Is it possible to plot without storing variables in arrays or lists? plt.scatter(x,y,c='r')
works but that doesn't produce any line plot.
Solution 1:[1]
Store the start and end of each segment to iteratively build a series of lines from datapoint to datapoint: (x0,y0)
-> (x1, y1)
import matplotlib.pyplot as plt
import numpy as np
x0, y0 = 0, 0
x1 = 0.0
dx = 0.5
for i in range(10):
y1 = x1**2
plt.plot([x0,x1],[y0,y1], 'o-')
x0, y0 = x1, y1
x1 += dx
plt.show()
Note: this example will draw a line from (0,0)
to (0,0)
as the x1
value chosen is starting at 0.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |