在matplotlib热图中限制列数

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

我正在尝试在matplotlib中绘制热图,并且参考了这个链接:将x轴移动到matplotlib图表的顶部

我的问题是,我的数据只有三列,但有70行。然而,当我使用这个例子时,图形总是显示70行和70列。有没有人知道怎么限制列的数量,让它们适合我的数据呢?

1 个回答

2

你发现了我代码中的一个错误。我把 data.shape 的索引搞反了。

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABC')
row_labels = range(7)
data = np.random.rand(7,3)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

这样会产生

在这里输入图片描述

撰写回答