gpt4 book ai didi

python - 如果行/列数是特定数字(通常是素数),Matplotlib pcolor/pcolormesh 就会崩溃

转载 作者:行者123 更新时间:2023-11-30 23:32:59 25 4
gpt4 key购买 nike

我有一个 pcolormesh 热图和树状图的代码,它工作得非常好,除了如果我有质数(或有时不是质数)的样本和/或基因,网格不再适合子图。经过多次尝试后,我意识到这与 pcolor/pcolormesh 划分其正方形的方式(舍入错误)有关,但我对 API 还不够熟悉,甚至无法开始解决问题。我真的希望这段代码可以推广到所有数量的样本/顶级基因。顺便说一句,这段代码不是我一个人写的,它是由大量问题拼凑而成的,所以谢谢你们(无论你们是谁)。

import scipy
import scipy.cluster.hierarchy as hier
import scipy.spatial.distance as dist

# xl is number of patients, yl is number of genes
# slicing: array[rows,cols]
xl = 20
yl = 50
X = np.transpose(np.random.uniform(-5,5,(100,100)))
#X = np.transpose(Ximp)
X = X[0:yl,0:xl]


fig = plt.figure()

plt.subplot2grid((10,1), (0,1))
X = np.transpose(X)
distMatrix = dist.pdist(X)
distSquareMatrix = dist.squareform(distMatrix)
linkageMatrix = hier.linkage(distSquareMatrix)
dendro = hier.dendrogram(linkageMatrix)
leaves = dendro['leaves']
plt.gca().set_xticklabels([])
plt.gca().set_yticklabels([])

plt.subplot2grid((10,1), (2,0), rowspan=8)
X = np.transpose(X)
X = X[:,leaves]
plt.pcolormesh(X, cmap=matplotlib.cm.RdBu_r, vmin=-5, vmax=5)
xlabels = [item[0:2] for item in demos[0]][0:xl]
relabelx = dict(zip(range(xl),xlabels))
ylabels = glist[0:yl]
plt.xticks(arange(0.5, xl+0.5, 1))
plt.yticks(arange(0.5, yl+0.5, 1))
plt.gca().set_xticklabels([relabelx[xval] for xval in leaves])
plt.gca().set_yticklabels(ylabels)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
plt.colorbar(cax=cbar_ax)

plt.show()

此代码生成此图像:

enter image description here

但是,我将 xl 更改为 22,将 yl 更改为 51(是的,我知道 22 不是素数,但我试图表明,即使我的问题通常与素数有关,但它并不限于它们),并且我明白了这个怪物:

enter image description here

有人知道如何解决这个问题吗?

最佳答案

只需添加:

plt.xlim(xmax=22) #or xl
plt.ylim(ymax=51) #or yl

之后

plt.pcolormesh(X, cmap=matplotlib.cm.RdBu_r, vmin=-5, vmax=5)

应该这样做。

关于python - 如果行/列数是特定数字(通常是素数),Matplotlib pcolor/pcolormesh 就会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124428/

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