如何创建第二个图表,然后在旧图表上绘图?

210 投票
6 回答
566019 浏览
提问于 2025-04-16 22:45

我想先画一张图,然后创建一个新的图形来画第二组数据,最后再回到最开始的图上画第三组数据,类似这样:

import numpy as np
import matplotlib as plt

x = arange(5)
y = np.exp(5)
plt.figure()
plt.plot(x, y)

z = np.sin(x)
plt.figure()
plt.plot(x, z)

w = np.cos(x)
plt.figure("""first figure""") # Here's the part I need
plt.plot(x, w)

顺便提一下,我怎么告诉matplotlib我完成了一幅图?也做了类似的事情,但不完全一样!它不让我访问最开始的那幅图。

6 个回答

25

不过,编号是从 1 开始的,所以:

x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)

z = np.sin(x)
plt.figure(2)
plt.plot(x, z)

w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)

另外,如果你的图上有多个坐标轴,比如子图,可以使用 axes(h) 命令,其中 h 是你想要关注的那个坐标轴的标识符。

(抱歉,我还没有评论的权限,所以只能这样回答!)

182

当你调用 figure 的时候,简单地给图形编号就行。

x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)

z = np.sin(x)
plt.figure(1)
plt.plot(x, z)

w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)

补充说明:你可以随意给图形编号(这里是从 0 开始),但是如果你在创建新图形的时候完全不提供编号,系统会自动从 1 开始编号(根据文档,这叫做“Matlab 风格”)。

194

如果你发现自己经常这样做,那可能值得去了解一下matplotlib的面向对象接口。在你的情况下:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")

z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis

虽然代码会稍微多一些,但这样写会更清晰,也更容易管理,特别是当你有多个图形,每个图形又有好几个子图的时候。

撰写回答