在Python中设置表格的x轴频率

1 投票
1 回答
507 浏览
提问于 2025-04-18 16:17

我有一段代码,可以在matplotlib.table对象中显示一个矩阵的数值:

fig = plt.figure(figsize=(20,11))
plt.title('Correlation Matrix')
ticks = np.array(['$F_{sum}$','$F_{dif}$','$x_{sum}$','$x_{dif}$','$y_{sum}$','$y_{dif}$','$HLR_a$','$e1_a$','$e2_a$',
                  '$HLR_b$','$e1_b$','$e2_b$'])
ticks = ticks[::-1]
ticks = ticks.tolist()                  
plt.xticks([0.5,1.2,2.1,3.0,3.9,4.8,5.7,6.6,7.5,8.4,9.3,10],ticks,fontsize=15)
plt.yticks([0.5,1.2,2.1,3.0,3.9,4.8,5.7,6.6,7.5,8.4,9.3,10],['$F_{sum}$','$F_{dif}$','$x_{sum}$','$x_{dif}$','$y_{sum}$','$y_{dif}$','$HLR_a$','$e1_a$','$e2_a$',
           '$HLR_b$','$e1_b$','$e2_b$'],fontsize=15)
round_mat = np.round(correlation_mat,2)
table = plt.table(cellText=round_mat,loc='center',colWidths=np.ones(correlation_mat.shape[0])/correlation_mat.shape[0],cellLoc='center',bbox=[0,0,1,1])
table.set_fontsize(25)
plt.show()

运行后得到的结果是:

在这里输入图片描述

我希望x轴和y轴的刻度能在每个矩形的中间对齐。现在看起来前面的几个刻度是对的,但后面的刻度就分散开了。我想要它们都能均匀分布,并且刻度在中间。我不知道该怎么做。

1 个回答

2

一种方法是使用表格的行和列标签。默认情况下,它们会有背景和边框,这样看起来有点笨重,想要去掉这些样式会比较麻烦:

import numpy as np
import matplotlib.pyplot as plt

# Generate some data...
data = np.random.random((12, 10))
correlation_mat = np.cov(data)
correlation_mat /= np.diag(correlation_mat)

fig, ax = plt.subplots(figsize=(20,11))
ax.set_title('Correlation Matrix')
ticks = ['$F_{sum}$', '$F_{dif}$', '$x_{sum}$', '$x_{dif}$', '$y_{sum}$',
         '$y_{dif}$', '$HLR_a$', '$e1_a$', '$e2_a$', '$HLR_b$', '$e1_b$',
         '$e2_b$'][::-1]

round_mat = np.round(correlation_mat, 2)
table = ax.table(cellText=round_mat, cellLoc='center', bbox=[0, 0, 1, 1],
                rowLabels=ticks, colLabels=ticks)
table.set_fontsize(25)

ax.axis('off')
for key, cell in table.get_celld().iteritems():
    if key[0] == 0 or key[1] == -1:
       cell.set(facecolor='none', edgecolor='none')
    if key[1] == -1:
       cell._loc = 'right'
    elif key[0] == 0:
       cell._loc = 'center'

plt.show()

这里输入图片描述

不过,有时候完全不使用表格来实现这个效果会更简单:

这里输入图片描述

import numpy as np
import matplotlib.pyplot as plt

# Generate some data...
data = np.random.random((12, 10))
correlation_mat = np.cov(data)
correlation_mat /= np.diag(correlation_mat)

num = data.shape[0]

fig, ax = plt.subplots(figsize=(20,11))
ticks = ['$F_{sum}$', '$F_{dif}$', '$x_{sum}$', '$x_{dif}$', '$y_{sum}$',
         '$y_{dif}$', '$HLR_a$', '$e1_a$', '$e2_a$', '$HLR_b$', '$e1_b$',
         '$e2_b$']
ticks = ticks[::-1]

ax.matshow(correlation_mat, aspect='auto', cmap='cool')
ax.set(title='Correlation Matrix', xticks=range(num), xticklabels=ticks,
       yticks=range(num), yticklabels=ticks)
ax.tick_params(labelsize=25)

for (i, j), val in np.ndenumerate(correlation_mat):
    ax.annotate('{:0.2f}'.format(val), (j,i), ha='center', va='center', size=25)

plt.show()

撰写回答