在上一个函数生成的绘图中添加一个子图

时间:2016-07-07 15:51:03

标签: python matplotlib

我编写了一个从csv文件中读取数据并绘制数据的函数。现在我需要添加一个子图,其中包含来自同一文件的另一部分数据,因此我尝试编写一个调用第一个函数并添加子图的函数。当我这样做时,我会让两个人显示为不同的数字。我怎样才能抑制它并使它们都显示在同一个图中?

这是我的代码的模型:

def timex(h_ratio = [3, 1]):

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.gridspec as gridspec

    total_height = h_ratio[0] + h_ratio[1]
    gs = gridspec.GridSpec(total_height, 1)

    time = [1, 2, 3, 4, 5]
    x = [1, 2, 3, 4, 5]
    y = [1, 1, 1, 1, 1]

    ax1 = plt.subplot(gs[:h_ratio[0], :])
    plt.plot(time, x)
    plot = plt.gcf
    plt.show()

    return time, x, y, plot, gs, h_ratio

def timeyx():
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec

    time, x, y, plot, gs, h_ratio = timex(h_ratio = [3, 1])
    ax2 = plt.subplot(gs[h_ratio[1], :])
    plt.plot(time, y) 
    plt.show()

timeyx()

我意识到我有两个plt.show()语句,但如果我删除一个那个数字根本就不显示。

1 个答案:

答案 0 :(得分:2)

我不确定您是否需要专门使用matplotlib.gridspec,但您可以使用subplot2grid来轻松完成工作。

import matplotlib.pyplot as plt

def timex():
    time = [1, 2, 3, 4, 5]
    x = [1, 2, 3, 4, 5]
    y = [1, 1, 1, 1, 1]

    ax1 = plt.subplot2grid((1,2), (0,0))
    ax1.plot(time, x)

    return time, x, y

def timeyx():

    time, x, y = timex()

    ax2 = plt.subplot2grid((1,2), (0,1))
    ax2.plot(time, y)

timeyx()
plt.show()

这将生成一个如下图所示的两个子图:

enter image description here