-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheatmap.py
306 lines (238 loc) · 9.04 KB
/
heatmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/env python
"""
produce a clustering heatmap
http://docs.scipy.org/doc/scipy-0.14.0/reference/cluster.hierarchy.html
"""
import sys
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, dendrogram
__author__ = "Adam Richards"
def blue_black_yellow():
cdict = {'red': ((0.0, 0.0, 0.0),\
(0.5, 0.0, 0.1),\
(1.0, 1.0, 1.0)),\
'green': ((0.0, 0.0, 0.0),\
(0.5, 0.1, 0.0),\
(1.0, 1.0, 1.0)),\
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return my_cmap
def red_black_green():
cdict = {'red': ((0.0, 0.0, 0.0),\
(0.5, 0.0, 0.1),\
(1.0, 1.0, 1.0)),\
'green': ((0.0, 0.0, 1.0),\
(0.5, 0.1, 0.0),\
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),\
(1.0, 0.0, 0.0))
}
my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return my_cmap
def red_black_blue():
cdict = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0)),
'black': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
my_cmap = mpl.colors.LinearSegmentedColormap('my_colormap',cdict,256)
return my_cmap
class Heatmap(object):
"""
produce a clustering heatmap
linkage metrics = 'average', 'single', 'centroid', 'complete'
"""
def __init__(self,mat,rowLabels,colLabels,width=6,height=7,title=None,dpi=300,
hpad=0.14,vpad=0.05,fontSize=10,fontName='sans-serif'):
"""
Constructor
"""
self.indx = {}
self.z = {}
self.fontSize = fontSize
self.fontName = fontName
self.mat = mat
if type(rowLabels) == type([]):
self.rowLabels = np.array(rowLabels)
else:
self.rowLabels = rowLabels
if type(colLabels) == type([]):
self.colLabels = np.array(colLabels)
else:
self.colLabels = colLabels
## initialize the axis (l,b,w,h)
self.plt = plt
self.fig = self.plt.figure(figsize=(width,height),dpi=dpi)
## set relative size of subplots (sum to 1.0)
base1 = 0.15
base2 = 0.85
## top dendogram
self.ax1 = self.fig.add_axes([base1,vpad+base2,base2-hpad,base1-vpad])
self.ax1.set_yticks([])
self.ax1.set_xticks([])
self.ax1.set_frame_on(False)
## side dendogram
self.ax2 = self.fig.add_axes([0,vpad,base1,base2])
self.ax2.set_yticks([])
self.ax2.set_xticks([])
self.ax2.set_frame_on(False)
## heatmap
self.ax3 = self.fig.add_axes([base1,vpad,base2-hpad,base2])
self.ax3.set_yticks([])
self.ax3.set_xticks([])
self.ax3.set_frame_on(False)
## colorbar
hsize = base1 # same as side dendogram width
vsize = base1-vpad # same as top dendogram height
left = 0.1 * hsize
bottom = vpad+base2 + (0.4 * vsize)
width = 0.80 * hsize
height = 0.5 * vsize
self.ax4 = self.fig.add_axes([left,bottom,width,height],frame_on=False)
self.ax4.set_yticks([])
self.ax4.set_xticks([])
self.ax4.set_frame_on(False)
self.title = None
## cluster the matrix
self.mat = mat
self.cluster(0)
self.cluster(1)
def cluster(self,dim,labels=None,link_color_func=None):
"""
use hierarchical clustering to group the data
dim = 0 are the rows
dim = 1 are the columns
"""
if dim == 0:
print("clustering the rows...")
x = self.mat
orientation='left'
self.plt.sca(self.ax2)
ax = self.ax2
if dim == 1:
print("clustering the columns...")
x = self.mat.transpose()
orientation='top'
self.plt.sca(self.ax1)
ax = self.ax1
distMatrix = pdist(x)
distMatrix = squareform(distMatrix)
linkageMatrix = linkage(distMatrix,method='complete')
if not link_color_func:
link_color_func = lambda k: 'k'
z = dendrogram(linkageMatrix,orientation=orientation,\
no_labels=True,color_threshold=1.0,\
link_color_func=link_color_func)
indx = z['leaves']
self.indx[str(dim)] = indx
self.z[str(dim)] = z
def draw_heatmap(self,cmap='uy',clabels=True,rlabels=False,rowFont=None,colFont=None):
"""
draw the heatmap portion of the plot
cmap can be a custom instance of a cmap
or 'yu' for yellow-black-blue'
or 'rg' for red-black-green
"""
if cmap == 'rg':
cmap = red_black_green()
elif cmap == 'uy':
cmap = blue_black_yellow()
elif cmap == 'ru':
cmap = red_black_blue()
else:
cmap = cmap
if rowFont == None:
rowFont = self.fontSize-2
if colFont == None:
colFont = self.fontSize
self.plt.sca(self.ax3)
ax = self.ax3
n,m = self.mat.shape
if '0' not in self.indx or '1' not in self.indx:
raise Exception("cluster before plotting heatmap")
## setup event handler
def mat_picker(x, mouseevent):
"""
find the row and column
"""
if mouseevent.xdata == None or mouseevent.ydata == None:
return False, dict()
colCoord = np.floor(mouseevent.xdata+.5)
rowCoord = np.floor(mouseevent.ydata+.5)
if len(self.colLabels) > 0:
col = self.colLabels[self.indx['1']][colCoord]
else:
col = np.arange(m)[self.indx['1']][colCoord]
if len(self.rowLabels) > 0:
row = self.rowLabels[self.indx['0']][rowCoord]
else:
row = np.arange(n)[self.indx['0']][rowCoord]
print("row: %s (%s), col: %s (%s)"%(col,int(colCoord),row,int(rowCoord)))
return False, dict()
## set vmin vmax
val = np.ceil(np.abs(self.mat).max())
maxval = float(val)
minval = -1.0*val
## reorder matrix
matReordered = self.mat[self.indx['0'],:]
matReordered = matReordered[:,self.indx['1']]
hmap = ax.imshow(matReordered,interpolation='nearest',aspect='auto',cmap=cmap,picker=mat_picker,origin='lower',
vmin=minval,vmax=maxval)
## handle axes
if clabels and len(self.colLabels) > 0:
ax.set_xticks(range(m))
ax.set_xticklabels(self.colLabels[self.indx['1']],fontsize=colFont,fontname=self.fontName,rotation='vertical')
if rlabels and len(self.rowLabels) > 0:
if n > 1000:
print ("WARNING: too many rows to visualize row labels")
rowFont = None
if rowFont:
ax.yaxis.set_ticks_position('right')
ax.set_yticks(range(n))
ax.set_yticklabels(self.rowLabels[self.indx['0']],fontsize=rowFont,fontname=self.fontName)
## colorbar
self.plt.sca(self.ax4)
ax = self.ax4
norm = mpl.colors.Normalize(vmin=minval,vmax=maxval)
cb1 = mpl.colorbar.ColorbarBase(ax,cmap=cmap,
ticks=[int(round(i)) for i in np.linspace(-1.0*val,val,5)],
norm=norm,
orientation='horizontal')
for t in ax.get_xticklabels():
t.set_fontsize(self.fontSize)
t.set_fontname(self.fontName)
for t in ax.get_yticklabels():
t.set_fontsize(self.fontSize)
t.set_fontname(self.fontName)
#print "min: %s,max: %s,mean: %s"%(round(mat.min(),2),round(mat.max(),2),round(mat.mean(),2))
def save(self,fileName,dpi=300):
"""
save the current plot to file
"""
self.plt.savefig(fileName,dpi=dpi)
def show(self):
"""
display the current plot
"""
self.plt.show()
if __name__ == "__main__":
print("Running...")
n = 10
m = 6
mat = np.vstack((np.random.normal(0,1,(n,m)),np.random.normal(3,1,(n,m))))
hm = Heatmap(mat,colLabels=np.array(["A","B","C","D","E","F"]),\
rowLabels= np.array(["r"+str(i) for i in range(n*2)]))
hm.draw_heatmap(cmap='rg',clabels = True, rlabels=True)
## error checking
hm.save("example.png")
hm.show()