繁体   English   中英

创建 matplotlib 子图而不手动计算子图的数量?

[英]Create matplotlib subplots without manually counting number of subplots?

在 Jupyter Notebook 中进行临时分析时,我经常想将转换到某些 Pandas DataFrame序列视为垂直堆叠的子图。 我通常的快速而肮脏的方法是根本不使用子图,而是为每个图创建一个新图:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({"a": range(100)})  # Some arbitrary DataFrame
df.plot(title="0 to 100")
plt.show()

df = df * -1  # Some transformation
df.plot(title="0 to -100")
plt.show()

df = df * 2  # Some other transformation
df.plot(title="0 to -200")
plt.show()

这种方法有局限性。 即使索引相同,x 轴刻度也未对齐(因为 x 轴宽度取决于 y 轴标签)并且 Jupyter 单元格输出包含多个单独的内嵌图像,而不是我可以保存或复制粘贴的单个图像.

据我所知,正确的解决方案是使用plt.subplots()

fig, axes = plt.subplots(3, figsize=(20, 9))

df = pd.DataFrame({"a": range(100)}) # Arbitrary DataFrame
df.plot(ax=axes[0], title="0 to 100")

df = df * -1 # Some transformation
df.plot(ax=axes[1], title="0 to -100")

df = df * 2 # Some other transformation
df.plot(ax=axes[2], title="0 to -200")

plt.tight_layout()
plt.show()

这正是我想要的输出。 然而,它也带来了一个让我默认使用第一种方法的烦恼:我必须手动计算我创建的子图的数量,并随着代码的变化在几个不同的地方更新这个计数。

在多图的情况下,添加第四个图就像第四次调用df.plot()plt.show()一样简单。 对于子图,等效更改需要更新子图计数,加上算术来调整输出图的大小,将plt.subplots(3, figsize=(20, 9))替换为plt.subplots(4, figsize=(20, 12)) . 每个新添加的子图都需要知道已经存在多少其他子图( ax=axes[0]ax=axes[1]ax=axes[2]等),因此任何添加或删除都需要对图进行级联更改以下。

看起来自动化应该很简单——它只是计数和乘法——但我发现用 matplotlib/pyplot API 不可能实现。 我能得到的最接近的是以下部分解决方案,它足够简洁但仍然需要显式计数:

n_subplots = 3  # Must still be updated manually as code changes

fig, axes = plt.subplots(n_subplots, figsize=(20, 3 * n_subplots))
i = 0  # Counts how many subplots have been added so far 

df = pd.DataFrame({"a": range(100)}) # Arbitrary DataFrame
df.plot(ax=axes[i], title="0 to 100")
i += 1

df = df * -1 # Arbitrary transformation
df.plot(ax=axes[i], title="0 to -100")
i += 1

df = df * 2 # Arbitrary transformation
df.plot(ax=axes[i], title="0 to -200")
i += 1

plt.tight_layout()
plt.show()

根本问题是,任何时候df.plot() ,都必须存在一个已知大小的axes列表。 我考虑以某种方式延迟df.plot()的执行,例如通过附加到可以在顺序调用之前计算的 lambda 函数列表,但这似乎是一种极端的仪式,只是为了避免更新整数手。

有没有更方便的方法来做到这一点? 具体来说,有没有办法创建一个具有“可扩展”数量的子图的图形,适用于事先不知道计数的临时/交互式上下文?

注:这个问题可能表现为任一重复这个问题,或者这一个,但是接受的答案,这两个问题恰好包含我试图解决的问题-即nrows=的参数plt.subplots()必须是在添加子图之前声明。)

IIUC 你需要一些容器来实现这个转换——例如一个list 就像是:

arbitrary_trx = [
    lambda x: x,         # No transformation
    lambda x: x * -1,    # Arbitrary transformation
    lambda x: x * 2]     # Arbitrary transformation

fig, axes = plt.subplots(nrows=len(arbitrary_trx))

for ax, f in zip(axes, arbitrary_trx):
    df = df.apply(f)
    df.plot(ax=ax)

在此处输入图片说明

您可以创建一个存储数据的对象,并且只有在您告诉它这样做时才创建图形。

import pandas as pd
import matplotlib.pyplot as plt

class AxesStacker():
    def __init__(self):
        self.data = []
        self.titles = []

    def append(self, data, title=""):
        self.data.append(data)
        self.titles.append(title)

    def create(self):
        nrows = len(self.data)
        self.fig, self.axs = plt.subplots(nrows=nrows)
        for d, t, ax in zip(self.data, self.titles, self.axs.flat):
            d.plot(ax=ax, title=t)



stacker = AxesStacker()

df = pd.DataFrame({"a": range(100)})  # Some arbitrary DataFrame
stacker.append(df, title="0 to 100")

df = df * -1  # Some transformation
stacker.append(df, title="0 to -100")

df = df * 2  # Some other transformation
stacker.append(df, title="0 to -200")

stacker.create()
plt.show()

首先创建一个空图,然后使用add_subplot添加子图。 使用新几何图形的新GridSpec更新subplotspec中现有子图的GridSpec (仅当您使用constrained布局而不是tight布局时才需要figure关键字)。

import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd


def append_axes(fig, as_cols=False):
    """Append new Axes to Figure."""
    n = len(fig.axes) + 1
    nrows, ncols = (1, n) if as_cols else (n, 1)
    gs = mpl.gridspec.GridSpec(nrows, ncols, figure=fig)
    for i,ax in enumerate(fig.axes):
        ax.set_subplotspec(mpl.gridspec.SubplotSpec(gs, i))
    return fig.add_subplot(nrows, ncols, n)


fig = plt.figure(layout='tight')

df = pd.DataFrame({"a": range(100)}) # Arbitrary DataFrame
df.plot(ax=append_axes(fig), title="0 to 100")

df = df * -1 # Some transformation
df.plot(ax=append_axes(fig), title="0 to -100")

df = df * 2 # Some other transformation
df.plot(ax=append_axes(fig), title="0 to -200")

在此处输入图片说明

将新子图添加为列的示例(并使用约束布局进行更改):

fig = plt.figure(layout='constrained')

df = pd.DataFrame({"a": range(100)}) # Arbitrary DataFrame
df.plot(ax=append_axes(fig, True), title="0 to 100")

df = df + 10 # Some transformation
df.plot(ax=append_axes(fig, True), title="10 to 110")

在此处输入图片说明

暂无
暂无

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

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