'Spaghetti plot of random figures in
I need a script which creates 3 plots in one frame ("spaghetti" plot) but current version returns something wrong. What am I doing incorrectly? Thanks.
import numpy as np
import matplotlib.pyplot as plt
a=[10]
for j in range(3):
for i in range(500):
i=np.random.randint(-100,100)
a.append(i)
b=np.cumsum(a)
plt.plot(b)
plt.show
Solution 1:[1]
If you mean 3 separated charts in on window then you need subplot(nrows, ncols, index) to create new place before every plot.
I create 1 row with 3 columns (it gives 3 places, and index shows in which place I want to plot)
You have also wrong indentations - you should rather create b after generating all values in a, and you should create a = [10] inside first for-loop to create new list for new plot.
And finally - you forgot () in plt.show()
import numpy as np
import matplotlib.pyplot as plt
for j in range(3):
a = [10]
for i in range(100):
value = np.random.randint(-100,100)
a.append(value)
b = np.cumsum(a)
plt.subplot(1,3,j+1)
plt.plot(b)
plt.show()
It may need other settings to resize plots and set 0 in the same place.
If you need more plot then you may use subplot() to create grid - ie subplot(3,3) create 3 rows with 3 plot in every row.
import numpy as np
import matplotlib.pyplot as plt
for j in range(3):
a = [10]
for i in range(100):
value = np.random.randint(-100,100)
a.append(value)
b = np.cumsum(a)
plt.subplot(3,3,j+1)
plt.plot(b)
plt.show()
If you mean 3 lines in one chart then you have to create new a for every line - but you use the same a for every line so finally they create one line.
import numpy as np
import matplotlib.pyplot as plt
for j in range(3):
a = [10]
for i in range(100):
value = np.random.randint(-100,100)
a.append(value)
b = np.cumsum(a)
plt.plot(b)
plt.show()
BTW: subplot() gives axis - so you can first create all place and keep all axis and alter plot lines in places, and eventually update them
import numpy as np
import matplotlib.pyplot as plt
import time
all_ax = []
for j in range(9):
ax = plt.subplot(3,3,j+1)
all_ax.append(ax)
plt.ion() # interactive ON (so `show()` will not block code)
plt.show() # show window # plt.show(block=False)
while True:
for j in range(9):
a = [10]
for i in range(100):
value = np.random.randint(-100,100)
a.append(value)
b = np.cumsum(a)
all_ax[j].clear() # remove previous line
all_ax[j].plot(b)
plt.pause(0.001)
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 |




