matplotlib 我怎样创造一个新的情节,然后在旧的情节?

u4vypkhs  于 11个月前  发布在  其他
关注(0)|答案(6)|浏览(122)

我想绘制数据,然后创建一个新的图形和绘图数据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?做了类似的事情,但不完全是!它不让我访问原始情节。

cqoc49vn

cqoc49vn1#

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

字符串
它有点冗长,但它更清晰,更容易跟踪,特别是有几个数字,每个数字都有多个子情节。

2w3rbyxf

2w3rbyxf2#

调用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样式”)。

ifmq2ha2

ifmq2ha23#

但是,编号从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是所需轴对象的句柄,以聚焦于该轴。
(don还没有评论权限,抱歉有新的答案!)

sg24os4d

sg24os4d4#

这里接受的答案是使用 * 面向对象接口 *(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的内部状态只支持单个图形的问题。

5m1hhzi4

5m1hhzi45#

为每次迭代绘制单独帧的简单方法可以是:

import matplotlib.pyplot as plt  
for grp in list_groups:
        plt.figure()
        plt.plot(grp)
        plt.show()

字符串
然后python将绘制不同的帧。

70gysomp

70gysomp6#

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

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

字符串

相关问题