我想绘制数据,然后创建一个新图形并绘制data2,最后回到原始图并绘制data3,有点像这样:
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我已经完成了绘图?做了类似的事情,但不完全是!它不允许我访问原始情节。
如果您发现自己经常做这样的事情,那么可能值得研究一下 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
它有点冗长,但更清晰、更容易跟踪,尤其是有多个图形,每个图形都有多个子图。
当您致电
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 风格”)。
但是,编号从
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
是所需轴对象的句柄以聚焦于该轴。
(还没有评论权限,抱歉新答案!)
这里接受的答案说使用面向对象的接口(
matplotlib
),但答案本身包含了一些MATLAB风格的接口(matplotib.pyplot
)。
可以单独使用 OOP 方法,如果你喜欢这样的东西:
import numpy as np
import matplotlib
x = np.arange(5)
y = np.exp(x)
first_figure = matplotlib.figure.Figure()
first_figure_axis = first_figure.add_subplot()
first_figure_axis.plot(x, y)
z = np.sin(x)
second_figure = matplotlib.figure.Figure()
second_figure_axis = second_figure.add_subplot()
second_figure_axis.plot(x, z)
w = np.cos(x)
first_figure_axis.plot(x, w)
display(first_figure) # Jupyter
display(second_figure)
这使用户可以手动控制图形,并避免与 pyplot
的内部状态仅支持单个图形相关的问题。
import matplotlib.pyplot as plt
for grp in list_groups:
plt.figure()
plt.plot(grp)
plt.show()
然后Python将绘制不同的帧。
def plotFigure(data_plot,file_name,order):
fig = plt.figure(order, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(data_plot)
fig.savefig(file_name, bbox_inches='tight')
plt.close()