Show 2 plots at same time instead of one after another in matplotlib
25,381
Solution 1
plt.show()
plots all the figures present in the state machine. Calling it only at the end of the script, ensures that all previously created figures are plotted.
Now you need to make sure that each plot indeed is created in a different figure. That can be achieved using plt.figure(fignumber)
where fignumber
is a number starting at index 1
.
import matplotlib.pyplot as plt
import mglearn
# generate dataset
X, y = mglearn.datasets.make_forge()
plt.figure(1)
mglearn.discrete_scatter(X[:, 0], X[:, 1], y)
plt.legend(["Class 0", "Class 1"], loc=4)
plt.xlabel("First feature")
plt.ylabel("Second feature")
plt.figure(2)
X, y = mglearn.datasets.make_wave(n_samples=40)
plt.plot(X, y, 'o')
plt.ylim(-3, 3)
plt.xlabel("Feature")
plt.ylabel("Target")
plt.show()
Solution 2
Create two figures
, and only call show()
once
fig1 = plt.figure()
fig2 = plt.figure()
ax1 = fig1.add_subplot(111)
ax2 = fig2.add_subplot(111)
ax1.plot(x1,y1)
ax2.plot(x2,y2)
plt.show()
Author by
user3848207
Updated on March 05, 2020Comments
-
user3848207 about 4 years
I have the following code which shows a matplotlib plot first. Then, I have to close the first plot so that the second plot appears.
import pandas as pd import numpy as np import matplotlib.pyplot as plt import mglearn # generate dataset X, y = mglearn.datasets.make_forge() # plot dataset mglearn.discrete_scatter(X[:, 0], X[:, 1], y) plt.legend(["Class 0", "Class 1"], loc=4) plt.xlabel("First feature") plt.ylabel("Second feature") print("X.shape: {}".format(X.shape)) plt.show() X, y = mglearn.datasets.make_wave(n_samples=40) plt.plot(X, y, 'o') plt.ylim(-3, 3) plt.xlabel("Feature") plt.ylabel("Target") plt.show()
I would like to have the 2 matplotlib plots appear at the same time.