如何告诉Matplotlib创建第二个(新)绘图,然后再在旧绘图上绘制?

2024-04-20 07:41:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想绘制数据,然后创建一个新的图形和绘图数据2,最后返回到原始的绘图和绘图数据3,有点像这样:

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)

仅供参考How do I tell matplotlib that I am done with a plot?做了类似的事情,但不完全一样!它不让我接触到原来的情节。


Tags: 数据importnumpy图形绘图plotmatplotlibas
3条回答

但是,编号从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是所需轴对象的句柄,用于聚焦该轴。

(还没有评论权限,很抱歉有新答案!)

当您调用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开始),但如果您在创建新绘图时根本没有为figure提供编号,则自动编号将从1开始(根据文档,为“Matlab样式”)。

如果您发现自己经常做这样的事情,那么可能值得研究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

这是一个有点冗长,但它更清楚,更容易保持跟踪,特别是与几个数字每个多个子批次。

相关问题 更多 >