Skip to main content
 首页 » 编程设计

python之如何标记图矩阵的行/列

2024年10月25日12zhoujg

我想制作一个图表矩阵,在每一行/每一列中我将绘制相应的条形图。基本上看起来像

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”。

你知道怎么做吗?

请您参考如下方法:

您可以使用/滥用标题和 ylabels,或者,如果您已经在使用它们,请使用 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() 

如果我们已经有了 ylabels 等,您可以使用 annotate 来放置行/列标签。 annotate 是一种简单的方法,允许将文本放置在距轴的边缘/中心/等点的固定偏移量(以及许多其他内容)。 See this page (以及其他几个)以获取有关 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 默认值修复它。)