【问题标题】:Arrange plots that have subplots called from functions on grid in matplotlib排列具有从 matplotlib 中网格上的函数调用的子图的图
【发布时间】:2017-03-14 10:26:58
【问题描述】:

我正在寻找类似于 R 中的arrangeGrob 的东西:

我有一个函数(比如函数FUN1),它可以创建一个带有子图的图。 FUN1 创建的子图数量可能会有所不同,而且图本身非常复杂。我还有另外两个函数FUN2FUN3,它们也创建了不同结构的图。

有没有一种简单的方法来定义/安排一个整体的 GRID,例如一个简单的 3 行 1 列样式并且简单地通过

FUN1 --> GRID(row 1, col 1)
FUN2 --> GRID(row 2, col 1)
FUN3 --> GRID(row 3, col 1)

之后,FUN1 生成的复杂图被绘制在第 1 行,FUN2 生成的图在第 2 行等等,之前没有在 FUN 中指定子图标准?

【问题讨论】:

  • 不可能在网格上布置未知数量的地块。您需要更具体地说明您想要实现的目标。

标签: python r matplotlib r-grid


【解决方案1】:

使用 matplotlib 创建绘图的常用方法是先创建一些轴,然后绘制到这些轴。可以使用plt.subplotsfigure.add_subplotplt.subplot2grid 或更复杂的方式在网格上设置轴,使用GridSpec

一旦创建了这些轴,就可以将它们赋予函数,将内容绘制到轴上。下面是一个示例,其中创建了 6 个轴并使用 3 个不同的函数来绘制它们。

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

def func1(ax, bx, cx):
    x = np.arange(3)
    x2 = np.linspace(-3,3)
    y1 = [1,2,4]
    y2 = [3,2.5,3.4]
    f = lambda x: np.exp(-x**2)
    ax.bar(x-0.5, y1, width=0.4)
    ax.bar(x, y2, width=0.4)
    bx.plot(x,y1, label="lab1")
    bx.scatter(x,y2, label="lab2")
    bx.legend()
    cx.fill_between(x2, f(x2))

def func2(ax, bx):
    x = np.arange(1,18)/1.9
    y = np.arange(1,6)/1.4
    z = np.outer(np.sin(x), -np.sqrt(y)).T
    ax.imshow(z, aspect="auto", cmap="Purples_r")
    X, Y = np.meshgrid(np.linspace(-3,3),np.linspace(-3,3))
    U = -1-X**2+Y
    V = 1+X-Y**2
    bx.streamplot(X, Y, U, V, color=U, linewidth=2, cmap="autumn")

def func3(ax):
    data = [sorted(np.random.normal(0, s, 100)) for s in range(2,5)]
    ax.violinplot(data)


gs = gridspec.GridSpec(3, 4, 
                width_ratios=[1,1.5,0.75,1],  height_ratios=[3,2,2] )

ax1 = plt.subplot(gs[0:2,0])
ax2 = plt.subplot(gs[2,0:2])
ax3 = plt.subplot(gs[0,1:3])
ax4 = plt.subplot(gs[1,1])
ax5 = plt.subplot(gs[0,3])
ax6 = plt.subplot(gs[1:,2:])

func1(ax1, ax3, ax5)
func3(ax2)
func2(ax4, ax6)

plt.tight_layout()
plt.show()

【讨论】:

  • 惊人的答案。感谢您的努力。我相信这也会对其他人有所帮助。
猜你喜欢
  • 2014-02-03
  • 2018-01-11
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
相关资源
最近更新 更多