在matplotlib中同时显示2个图而不是一个接一个 [英] Show 2 plots at same time instead of one after another in matplotlib

查看:172
本文介绍了在matplotlib中同时显示2个图而不是一个接一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,该代码首先显示了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()

我希望同时出现 2 个 matplotlib 图.

I would like to have the 2 matplotlib plots appear at the same time.

推荐答案

plt.show() 绘制出现在状态机中的所有图形.仅在脚本末尾调用它,可确保绘制所有先前创建的图形.

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.

现在您需要确保每个图确实是在不同的图形中创建的.这可以使用 plt.figure(fignumber) 实现,其中 fignumber 是从索引 1 开始的数字.

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

这篇关于在matplotlib中同时显示2个图而不是一个接一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆