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



我想绘制数据,然后创建一个新图形并绘制数据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)

仅供参考我如何告诉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将绘制不同的帧

经过一些挣扎后,我发现的一种方法是创建一个函数,该函数获取data_plot矩阵,文件名和顺序作为参数,从有序图(不同的顺序=不同的数字)中的给定数据创建箱线图,并将其保存在给定的file_name下。

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()

相关内容

最新更新