Rav*_*Jha 5 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])
Run Code Online (Sandbox Code Playgroud)
但是,我想通过以下方式向所有行(而不是绘图)添加标题(标题为黄色文本):
我在这里找到了这张图片和一些执行此操作的方法,但我无法为我的用例实现此操作并收到错误。这是我尝试过的:
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}')
Run Code Online (Sandbox Code Playgroud)
这给了我错误:'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}')
Run Code Online (Sandbox Code Playgroud)
但这返回了错误:'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])
Run Code Online (Sandbox Code Playgroud)
这使:
| 归档时间: |
|
| 查看次数: |
1688 次 |
| 最近记录: |