【问题标题】:Matplotlib: Plotting the same graph in two different figures without writting the "plot(x,y)" line twiceMatplotlib:在两个不同的图形中绘制相同的图而不用两次写“plot(x,y)”线
【发布时间】:2013-01-31 20:21:40
【问题描述】:

我有这个简单的代码,它在两个不同的图形(图 1 和图 2)中绘制完全相同的东西。但是,我必须写两次 ax?.plot(x, y) 行,一次用于 ax1,一次用于 ax2。我怎么能只有一个情节表达式(有多个冗余的可能是我更复杂的代码的麻烦来源)。像 ax1,ax2.plot(x, y) .​​.. 之类的东西?

import numpy as np
import matplotlib.pyplot as plt

#Prepares the data
x = np.arange(5)
y = np.exp(x)

#plot fig1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

#plot fig2
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)

#adds the same fig2 plot on fig1
ax1.plot(x, y)
ax2.plot(x, y)

plt.show()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以将每个轴添加到列表中,如下所示:

    import numpy as np
    import matplotlib.pyplot as plt
    
    axes_lst = []    
    #Prepares the data
    x = np.arange(5)
    y = np.exp(x)
    
    
    #plot fig1
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    axes_lst.append(ax1)
    
    #plot fig2
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(111)
    axes_lst.append(ax2)
    
    for ax in axes_lst:
        ax.plot(x, y)
    
    plt.show()
    

    或者你可以使用这个不受支持的特性来提取 pyplot 中的所有图形。取自https://stackoverflow.com/a/3783303/1269969

    figures=[manager.canvas.figure
             for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
    for figure in figures:
        figure.gca().plot(x,y)
    

    【讨论】:

    • 我不知道我能做到这一点。非常感谢!
    • 如果您在谈论第二种方法,请记住,没有保证这将适用于未来的版本。 __pylab_helpers 表明它应该是私有的,所以你不能依赖它一直工作。
    • 我会强烈建议您为不影响pyplot 函数的列表和循环变量选择不同的名称。此外,您的第二个示例不起作用,您需要执行 figure.gca().plot(x, y) 并将绘制到 每个 打开的图形中,而不仅仅是您可能想要的两个。
    • 为什么建议我更改列表和循环变量?它们与 pyplot 位于不同的命名空间中,您只是担心混淆吗?我已经编辑了第二个。我同意第二个可能不应该使用,但我想我会包括它,因为我发现它的存在很有趣。
    • 因为很多人(包括我自己)在ipython --pylab 工作,它从pyplot 导入所有内容,所以虽然你在技术上是正确的,但这可能会让一些人感到困惑。而且,这只是令人困惑。请改用figfigs,减少打字次数,减少新手复制粘贴代码并破坏他们的交互会话的机会,也不会造成混淆。
    【解决方案2】:

    在不了解 matplotlib 的情况下,您可以将所有轴 (?) 添加到列表中:

    to_plot = []
    to_plot.append(ax1)
    ...
    to_plot.append(ax2)
    ...
    
    # apply the same action to each ax
    for ax in to_plot: 
        ax.plot(x, y)
    

    然后,您可以添加任意数量的内容,每个人都会发生同样的事情。

    【讨论】:

    • 我不知道我能做到这一点。非常感谢!
    猜你喜欢
    • 2015-05-31
    • 2020-12-02
    • 2015-04-04
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 2021-08-18
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多