matplotlib 向子图网格添加全局X/Y标签[重复]

dohp0rv5  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(164)
    • 此问题在此处已有答案**:

(9个答案)
昨天关门了。
为了比较结果,我试图在一个网格图中画出许多实验的摘要,我的目标是得到一个如下所示的图:

我已经成功地使用subfigures和行标题创建了图表的网格(甚至是每行中的每个图表),但是,我无法显示X/Y标签。
我一直在使用的代码如下:

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

plt.rcParams["figure.figsize"] = (20,20) # Increasing the size of the graph to accomodate all properly.

fig = plt.figure(constrained_layout=True)
fig.suptitle(f'The big title of the set')

# Attempt 1:
plt.xlabel('The X-Label for all graphs')
ply.ylabel('The Y-Label for all graphs')

# Attempt 2:
axes = fig.gca()
axes.set_xlabel('The X-Label for all graphs', loc='left') # I was wondering if the placement was problematic.
axes.set_ylabel('The Y-Label for all graphs', visible=True) # Or maybe the visibility?

Rows = [four, parts, of, data]
Columns = [four, parts, of, values, per, row]

subfigs = fig.subfigures(nrows=len(Xs), ncols=1)
    
for row, subfig in zip(Rows, subfigs):
    subfig.suptitle(f'Title of row {row}')
    subsubfigs = subfig.subplots(nrows=1, ncols=len(Columns))
        
    for column, subsubfig in zip(Columns, subsubfigs):
        subsubfig.plot(row_data, column_data)
        subsubfig.set_title(f'Title of single graph {row}:{column}')
            
plt.show()

但是,我没有得到任何标签,我确实成功地使用subsubfig.set_xlabelsubsubfig.set_ylabel为每个子图添加了标签,但是我想知道为什么不能在大网格上使用它。

zed5wv10

zed5wv101#

可以使用fig.supxlabel()fig.supylabel()作为常用的x和y标签:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(nrows=4, ncols=1, figsize=(10,10))
fig.suptitle(f'The big title of the set', size=20)
fig.supxlabel('The X-Label for all graphs', x=0.5, y=0.9, size=10)
fig.supylabel('The Y-Label for all graphs', size=10)

for idx, ax in enumerate(axs):
    # There is also ax.set_title for title axis
    ax.text(x=0.5, y=0.7, s=f'Title of Row {idx}', ha='center')
    ax.text(x=0.5, y=0.5, s='Row of 4 graphs', ha='center')

plt.show()

有关Matplotlib docs on supxlabel and supylabel的更多信息。

ltqd579y

ltqd579y2#

要设置整个图形的xlabelylabel,我们可以在fig上使用supxlabelsupylabel,就像使用suptitle一样:

fig.supxlabel(...)
fig.supylabel(...)

我喜欢使用GridSpec,因为它的处理方式类似于典型的matplotlibsubplot,您可以在subplotax es上使用set_xlabel

from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(20, 10), constrained_layout=True)
fig.suptitle(f'The big title of the set')
gs = GridSpec(4, 1, figure=fig)
for row, subfig in ...:
    ax = fig.add_subplot(gs[row, 0])
    ax.set_xlabel(...)
    ...
            
plt.show()

相关问题