gpt4 book ai didi

python - 在 Python 表格中设置 x 轴频率

转载 作者:行者123 更新时间:2023-12-01 05:05:14 25 4
gpt4 key购买 nike

我有以下代码,用于显示 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()

输出如下:

enter image description here

我希望每个矩形的 x 轴和 y 轴刻度都居中。在这里,似乎前几个刻度是正确的,然后其余的则分散开来。我希望它们都等距,并且刻度线位于中心。我不知道该怎么做。

最佳答案

执行此操作的一种方法是使用表的行标签和列标签。默认情况下,它们有背景和边框,关闭它有点笨拙:

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()

enter image description here

但是,有时完全跳过使用表格来完成此操作会更容易: enter image description here

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()

关于python - 在 Python 表格中设置 x 轴频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com