【问题标题】:How to add row titles to the following the matplotlib code?如何将行标题添加到以下 matplotlib 代码?
【发布时间】:2021-10-31 18:52:16
【问题描述】:

我正在尝试创建一个包含 8 个子图(4 行和 2 列)的图。为此,我编写了这段代码来读取 x 和 y 数据并以下列方式绘制它:

fig, axs = plt.subplots(4, 2, figsize=(15,25))
y_labels = ['k0', 'k1']

for x in range(4):
    for y in range(2):
        axs[x, y].scatter([i[x] for i in X_vals], [i[y] for i in y_vals])
        axs[x, y].set_xlabel('Loss')
        axs[x, y].set_ylabel(y_labels[y])

这给了我以下结果:

但是,我想通过以下方式(黄色文本中的标题)为所有行(而不是地块)添加标题:

我找到了这张图片和一些方法来做到这一点here,但我无法为我的用例实现这个并得到一个错误。这是我尝试过的:

gridspec = axs[0].get_subplotspec().get_gridspec()
subfigs = [fig.add_subfigure(gs) for gs in gridspec]

for row, subfig in enumerate(subfigs):
    subfig.suptitle(f'Subplot row title {row}')

这给了我错误:'numpy.ndarray' object has no attribute 'get_subplotspec'

所以我把代码改成了:

gridspec = axs[0, 0].get_subplotspec().get_gridspec()
    subfigs = [fig.add_subfigure(gs) for gs in gridspec]
    
    for row, subfig in enumerate(subfigs):
        subfig.suptitle(f'Subplot row title {row}')

但这返回了错误:'Figure' object has no attribute 'add_subfigure'

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    您链接的答案中的解决方案是正确的,但是它特定于 3x3 案例,如图所示。以下代码应该是针对不同数量的子图的更通用的解决方案。如果您的数据和y_label 数组/列表的大小都正确,这应该可以工作。

    请注意,这需要 matplotlib 3.4.0 及更高版本才能工作:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # random data. Make sure these are the correct size if changing number of subplots
    x_vals = np.random.rand(4, 10)
    y_vals = np.random.rand(2, 10)
    y_labels = ['k0', 'k1']  
    
    # change rows/cols accordingly
    rows = 4
    cols = 2
    
    fig = plt.figure(figsize=(15,25), constrained_layout=True)
    fig.suptitle('Figure title')
    
    # create rows x 1 subfigs
    subfigs = fig.subfigures(nrows=rows, ncols=1)
    
    for row, subfig in enumerate(subfigs):
        subfig.suptitle(f'Subplot row title {row}')
    
        # create 1 x cols subplots per subfig
        axs = subfig.subplots(nrows=1, ncols=cols)
        for col, ax in enumerate(axs):
            ax.scatter(x_vals[row], y_vals[col])
            ax.set_title("Subplot ax title")
            ax.set_xlabel('Loss')
            ax.set_ylabel(y_labels[col])
    

    这给出了:

    【讨论】:

    • 知道了,我对子图有点困惑,还更新了 matplotlib。谢谢。此外,对于我的用例,我必须将行 ax.scatter(x_vals[row], y_vals[col]) 更改为 ax.scatter([i[row] for i in X_vals], [i[col] for i in y_vals])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多