Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 262
user3848207 Avatar asked Mar 04 '17 10:03

user3848207


People also ask

How do I show two plots in matplotlib?

The matplotlib. pyplot. plot() function provides a unified interface for creating different types of plots. The simplest example uses the plot() function to plot values as x,y coordinates in a data plot.


2 Answers

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()
like image 127
ImportanceOfBeingErnest Avatar answered Sep 30 '22 18:09

ImportanceOfBeingErnest


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()
like image 36
Crispin Avatar answered Sep 30 '22 18:09

Crispin