Heatmap
Thermal OTU Clustermap
Hierarchical clustering of OTU abundance with thermal color palette
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, leaves_list
from scipy.spatial.distance import pdist
from matplotlib.colors import LinearSegmentedColormap
np.random.seed(42)
n_rows, n_cols = 35, 10
data = np.random.randn(n_rows, n_cols)
data[:8, :3] += 2
data[18:28, 5:9] -= 2
data[10:18, 2:6] += 1.5
colors = ['#cffafe', '#22d3ee', '#fbbf24', '#f97316', '#dc2626']
cmap = LinearSegmentedColormap.from_list('Thermal', colors, N=256)
row_linkage = linkage(pdist(data), method='ward')
col_linkage = linkage(pdist(data.T), method='ward')
row_order = leaves_list(row_linkage)
col_order = leaves_list(col_linkage)
data_ordered = data[row_order][:, col_order]
fig = plt.figure(figsize=(10, 11), facecolor='white')
ax_heatmap = fig.add_axes([0.15, 0.08, 0.55, 0.60])
ax_col_dend = fig.add_axes([0.15, 0.70, 0.55, 0.12])
ax_row_dend = fig.add_axes([0.02, 0.08, 0.12, 0.60])
ax_cbar = fig.add_axes([0.82, 0.25, 0.02, 0.25])
im = ax_heatmap.imshow(data_ordered, cmap=cmap, aspect='auto', vmin=-3, vmax=3)
ax_heatmap.set_xticks(range(n_cols))
ax_heatmap.set_xticklabels([f'{(i+1)*50}' for i in range(n_cols)], fontsize=8, rotation=45)
ax_heatmap.set_yticks(range(0, n_rows, 5))
ax_heatmap.set_yticklabels([f'Otu{row_order[i]:05d}' for i in range(0, n_rows, 5)], fontsize=7)
ax_heatmap.yaxis.tick_right()
ax_heatmap.tick_params(length=0)
for spine in ax_heatmap.spines.values():
spine.set_linewidth(0.5)
spine.set_color('#ccc')
dendrogram(col_linkage, ax=ax_col_dend, color_threshold=0,
above_threshold_color='k', link_color_func=lambda k: 'k', no_labels=True)
ax_col_dend.axis('off')
dendrogram(row_linkage, ax=ax_row_dend, orientation='left', color_threshold=0,
above_threshold_color='k', link_color_func=lambda k: 'k', no_labels=True)
ax_row_dend.axis('off')
cbar = plt.colorbar(im, cax=ax_cbar)
cbar.ax.tick_params(labelsize=8)
cbar.outline.set_linewidth(0.5)
plt.show()
Library
Matplotlib
Category
Heatmaps & Density
More Heatmap examples
☕