简体   繁体   English

如何 plot 不同 plot 在单个 plot ZF02113237A5A6FFF03E34CEEEB4

[英]how to plot different plot in a single plot matplotlib

I created 2 different plot in this way:我以这种方式创建了 2 个不同的 plot:

def first():
    fig, axes = plt.subplots(1, figsize=(10, 5))
    ...
    ...
    return fig, axes

def second():
    fig, axes = plt.subplots(1, figsize=(10, 5))
    ...
    ...
    return fig, axes

What I would like to do is to 'collect' these 2 plots in a single one.我想做的是将这两个地块“收集”在一个地块中。 I try these solutions:我尝试这些解决方案:

1: 1:

fig, ax = plt.subplots(2, figsize=(15, 20))
ax[0].plot = first()
ax[1].plot = second()
plt.show()

2: 2:

fig, ax = plt.subplots(2, figsize=(15, 20))
ax[0].plot = first()
ax[1].plot = second()
for ax in ax:
    ax.label_outer()
plt.show()

but anytime I got 3 different figures: one figures with 2 axes but empty但任何时候我都会得到 3 个不同的数字:一个有 2 个轴但为空的数字在此处输入图像描述 and 2 figures with the right plot but not where I wanted to be和右边的 2 个数字 plot 但不是我想去的地方

在此处输入图像描述

在此处输入图像描述

Can someone help and suggest what I get wrong in my code?有人可以帮助并建议我在代码中出错的地方吗? thanks谢谢

Here is a simple example of how you may proceed to achieve what you aim.这是一个简单的示例,说明您如何继续实现您的目标。

Lets create a function having axe switch to cope with existing matplotlib axe or create it if missing.让我们创建一个具有axe开关的 function 以应对现有的 matplotlib 斧头,或者在缺少时创建它。

import matplotlib.pyplot as plt

def first(x, y, axe=None):
    if axe is None:
        fig, axe = plt.subplots()
    axe.plot(x, y)
    axe.set_ylabel("First")
    axe.grid()
    return axe

Similarly we create the second function:同样,我们创建第二个 function:

def second(x, y, axe=None):
    if axe is None:
        fig, axe = plt.subplots()
    axe.plot(x, y)
    axe.set_ylabel("Second")
    axe.grid()
    return axe

The we create some synthetic data for display purpose:我们为显示目的创建了一些合成数据:

import numpy as np

t = np.linspace(0, 2*np.pi, 250)
x1 = 3*np.sin(5*t)
x2 = 0.5*np.cos(15*t)

Then comes the magic, we create both axes and send references to their respective functions:然后是魔术,我们创建两个轴并发送对它们各自函数的引用:

fig, axe = plt.subplots(2, 1, sharex=True, sharey=True)
first(t, x1, axe=axe[0])
second(t, x2, axe=axe[1])

Afterward we are still able to add features to axes:之后我们仍然可以向轴添加功能:

axe[0].set_title("Some functional plots")
axe[1].set_xlabel("Time")

Final result looks like:最终结果如下所示:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM