1

I have a code for a pcolormesh heatmap and dendrogram which works pretty great, except that if I have a prime number (or sometimes not a prime number) of samples and/or genes, the mesh no longer fits the subplot. After playing around a lot, I realized this had to do with the way that pcolor/pcolormesh divides its squares (rounding errors), but I'm not familiar enough with the API to even begin to fix the problem. I would really like to have this code be generalizable for ALL numbers of samples/top genes. Btw, I didn't write this code alone, it was cobbled together from tons of SO questions, so thanks guys (whoever you are).

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

This code produces this makes this image:

enter image description here

However, I change xl to 22 and yl to 51 (and yes, I know 22 is not prime, but I'm trying to show that even though my problem is usually with primes, it's not exclusive to them), and I get this monstrosity:

enter image description here

Does anyone have any clue how to fix this?

4

1 回答 1

3

只需添加:

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

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

应该这样做。

于 2013-10-01T20:54:33.107 回答