如何给图矩阵的行/列加标签?

3 投票
1 回答
1792 浏览
提问于 2025-04-18 13:46

我想制作一个图表矩阵,每一行和每一列都会绘制相应的柱状图。基本上,它看起来像这样:

import matplotlib.pyplot as plt
fig, axarr = plt.subplots(3,3)
for i in range(3):
    for j in range(3):
        axarr[i,j].bar([1,2,3], [1,3,7])
    plt.tight_layout()

现在我还想在左边给行加上标签,在上面给列加上标签。就像一个表格,列的标题可能是“a”、“b”、“c”,而行的标题可能是“d”、“e”、“f”。

你知道怎么做到这一点吗?

1 个回答

3

你可以使用标题和y轴标签,或者如果你已经在用这些标签的话,可以用annotate这个功能,把文本放在坐标轴的顶部或左边,保持一定的距离。

下面是这两种方法的例子:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True)

for ax in axes.flat:
    ax.bar(range(5), np.random.random(5), color=np.random.random((5,3)))

for ax, col in zip(axes[0,:], ['A', 'B', 'C']):
    ax.set_title(col, size=20)
for ax, row in zip(axes[:,0], ['D', 'E', 'F']):
    ax.set_ylabel(row, size=20)

plt.show()

在这里输入图片描述

如果我们已经有了y轴标签等内容,可以用annotate来放置行或列的标签。annotate是一个简单的方法,可以让文本距离坐标轴的边缘或中心等位置保持固定的距离(还有很多其他功能)。想了解更多关于annotate的信息,可以查看这个页面(还有其他几个页面)。

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True)

for ax in axes.flat:
    ax.bar(range(5), np.random.random(5), color=np.random.random((5,3)))
    ax.set(xlabel='X-axis', ylabel='Y-axis')

for ax, col in zip(axes[0,:], ['A', 'B', 'C']):
    ax.annotate(col, (0.5, 1), xytext=(0, 10), ha='center', va='bottom',
                size=20, xycoords='axes fraction', textcoords='offset points')

for ax, row in zip(axes[:,0], ['D', 'E', 'F']):
    ax.annotate(row, (0, 0.5), xytext=(-45, 0), ha='right', va='center',
                size=20, rotation=90, xycoords='axes fraction',
                textcoords='offset points')

plt.show()

在这里输入图片描述

(顺便说一下,关于行标签的-45点偏移:如果需要的话我们可以计算出来,但目前我就不计算了,直接用matplotlib的默认设置。)

撰写回答