python - 如何将行标题添加到以下 matplotlib 代码中?

标签 python matplotlib subplot

我正在尝试创建一个包含 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])
这给了我以下结果:
enter image description here
但是,我想通过以下方式(黄色文本的标题)为所有行(而不是图)添加标题:
enter image description here
我找到了这张图片和一些方法 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'

最佳答案

您链接的答案中的解决方案是正确的,但它特定于 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])
这使:
enter image description here

关于python - 如何将行标题添加到以下 matplotlib 代码中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69027829/

相关文章:

python - 提高 pandas 数据框的性能

python - PySide - 获取表中所有可见行的列表

python - 在 Matplotlib 中显示所有 xlabels 和 xticks

python - Matplotlib (GridSpec) - 子图轴标签被截断?尝试过 `tight_layout`

python - plotly,python,在其他子图上绘制直方图?

python - 如何在 Python 中安全地使用 exec()?

python - 在 Pandas 分类中,格式 ="table"是什么?

python - matplotlib close 不关闭窗口

python - 使用matplotlib无法完全显示无花果边界处的标记

python - 如何设置 pyplot 子图的 xticks 和字体属性?