我该如何告诉Matplotlib创建第二个(新的)图,然后再在旧的图上创建图? [英] How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
问题描述
我想绘制数据,然后创建一个新图形并绘制data2,最后回到原始绘制并绘制data3,有点像这样:
I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this:
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)
FYI 我如何知道matplotlib我已经完成了一个情节吗?它不允许我访问原始图块.
FYI How do I tell matplotlib that I am done with a plot? does something similar, but not quite! It doesn't let me get access to that original plot.
推荐答案
如果您发现自己经常做这样的事情,那么可能值得研究一下matplotlib的面向对象的接口.就您而言:
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
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
它稍微冗长一些,但更容易跟踪,尤其是几张带有多个子图的图形时.
It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.
这篇关于我该如何告诉Matplotlib创建第二个(新的)图,然后再在旧的图上创建图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!