Reputation: 55
In the following code why I have to define fig
and ax
at the beginning of for loop? When I write it at the end of loop it gives me only one graph not the two.
fig = plt.figure()
ax = fig.add_subplot(111)
Ls = [2, 4]
for L in range(len(Ls)):
x = np.arange(10)
y = np.random.randint(0, 11, size=10)
print(y)
ax.plot(x,y)
ax.set_label("x")
ax.set_label("y")
plt.savefig("jj.png")
plt.show()
Upvotes: 0
Views: 462
Reputation: 6298
Consider defining the figure as getting a sheet of paper to draw upon. So, if you want to draw several plots into the same diagram you need to define it once (before the loop) and draw several plot onto it (in the loop). For this to work, you need to move savefig()
and show
out of the loop body:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
Ls = [2, 4]
for L in range(len(Ls)):
x = np.arange(10)
y = np.random.randint(0, 11, size=10)
print(y)
ax.plot(x,y)
ax.set_label("x")
ax.set_label("y")
plt.savefig("jj.png")
plt.show()
Which will give you something like this:
If you want two plots, you can use the subplots()
method to create several axes on which you can then call plot()
like this:
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(2, 1) # This creates two axes objects, one for the upper one for the lower plot
for ax in axes:
x = np.arange(10)
y = np.random.randint(0, 11, size=10)
ax.plot(x,y)
ax.set_xlabel("x")
ax.set_ylabel("y")
fig.tight_layout()
plt.savefig("jj.png")
plt.show()
This will give you something like this:
Upvotes: 2
Reputation: 493
Your for loop has two steps.
If you create fig = plt.figure()
inside the loop, there will be two plots, one per iteration; if you put fig = plt.figure()
outside the for loop, then plt.plot(...)
will plot in the only figure that was created.
When the plt.figure()
is outside the for loop, there are still two plots but one figure, but because of the line plt.show()
one plot is replacing the other or plotting over the other.
If you delete the line plt.show()
you'll see the two plots in the same figure.
Upvotes: 0