Python:同时绘制多个图形(matplotlib)

时间:2013-04-04 14:23:42

标签: python graph matplotlib plot

我有一个带参数p的函数,然后用plt.plot()输出一个图形。

然而,我想传递一个包含许多p值的列表并让它同时绘制所有图形(例如,像图形矩阵,我不知道它实际上被称为什么。一种网格很多图)。怎么办呢?

例如,这是我当前的功能(简化):

def graph(p):
    x = np.array(get x values from p here) #pseudocode line
    y = np.array(get y values from p here) #pseudocode line

    plt.title("title")
    plt.ylabel("ylabel")
    plt.xlabel("xlabel")
    plt.plot(x, y, 'ro', label = "some label")
    plt.legend(loc='upper left')
    plt.show()

2 个答案:

答案 0 :(得分:1)

如果你知道你想要多少个情节,你可以做这样的事情

def graph(p):
    x = np.array(get x values from p here) #pseudocode line
    y = np.array(get y values from p here) #pseudocode line

    plt.title("title")
    plt.ylabel("ylabel")
    plt.xlabel("xlabel")
    plt.plot(x, y, 'ro', label = "some label")
    plt.legend(loc='upper left')

    # Removed the show line from here
    # plt.show()


# Number of subplots. This creates a grid of nx * ny windows
nx = 3
ny = 2

# Iterate over the axes
for y in xrange(nx):
    for x in xrange(ny):
        plt.subplot(nx, ny, y * ny + x + 1)  # Add one for 1-indexing
        graph(p)

# Finally show the window
plt.show()

答案 1 :(得分:0)

def graph(p, ax=None):
    if ax is None:
        ax = plt.gca()
    x = np.linspace(0, np.pi * 2, 1024)
    y = np.sin(x) + p

    ax.set_title("title")
    ax.set_ylabel("ylabel")
    ax.set_xlabel("xlabel")
    ax.plot(x, y, 'ro', label = "some label")
    ax.legend(loc='upper left')

# Number of subplots. This creates a grid of nx * ny windows
nx = 3
ny = 2

fig = plt.gcf()
# Iterate over the axes
for j in xrange(nx * ny):
    t_ax = fig.add_subplot(nx, ny, j + 1)  # Add one for 1-indexing
    graph(j, t_ax)

plt.show()
fig.tight_layout()
plt.draw()

See here for guide on tight_layout