Skip to content Skip to sidebar Skip to footer

Show 2 Plots At Same Time Instead Of One After Another In Matplotlib

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 m

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()

Post a Comment for "Show 2 Plots At Same Time Instead Of One After Another In Matplotlib"