【问题标题】:Python: Graphing many graphs at the same time (matplotlib)Python:同时绘制多个图形(matplotlib)
【发布时间】:2013-04-04 14:23:42
【问题描述】:

我有一个函数,它接受一个参数 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()

【问题讨论】:

  • 我无法让子图按我想要的方式工作,并认为这不是我需要的——我该如何正确使用它来完成我需要的工作?
  • 向我们展示您的尝试
  • 我无法尝试任何事情,因为我不知道如何将其应用于我当前的地块
  • 你要看的是OO接口,不是matplotlib的状态机接口。如果您为问题中的代码提供 some 基础,您将获得更好的帮助,即使它只是伪代码

标签: python graph matplotlib plot


【解决方案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()

【讨论】:

  • 哇,这真的很接近了!有没有办法让它修复标签和轴等的缩放比例?它们似乎和以前一样大,而且看起来很奇怪,但到目前为止感谢您!
  • 您确实应该获取subplot 返回的axes 对象,然后将graph 修改为graph(p, ax),这样您就不会依赖全局状态。
  • 如果你有足够新的 matplotlib 版本,紧凑布局将解决一些布局问题。
  • @tcaswell 我不是 CS 人,你能解释一下你的意思吗?可以举个例子吗?
【解决方案2】:
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

【讨论】:

  • "name 'gcf' is not defined"(我使用 import matplotlib.pyplot as plt )
  • 应该是plt.gcf()。我在 ipython 中工作,将一大堆东西直接导入名称空间,有时我忘记重新附加 plt
  • 文本问题仍然与其他答案相同——图例很大,轴数很大,标题与上方图形的轴重叠,等等。有没有办法自动缩放像这样缩小子图或在图形之间添加填充时的文本?
  • 是的,见链接。如果你有更多问题,你应该打开一个新问题。
  • 虽然我在 plt.show() 之前调用了 plt.tight_layout(),但不确定这是否重要(而不是在 show() 之后调用 fig.tight_layout())
猜你喜欢
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 2020-09-15
相关资源
最近更新 更多