我如何告诉 Matplotlib 创建第二个(新)绘图,然后在旧绘图上绘图? [英] How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
问题描述
我想绘制数据,然后创建一个新图形并绘制data2,最后回到原来的plot并绘制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)
仅供参考 我如何判断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屋!