Heatmap
Annotated OTU Clustermap
Hierarchical clustering of OTU abundance with species and density annotations
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 = ['#2166ac', '#67a9cf', '#d1e5f0', '#f7f7f7', '#fddbc7', '#ef8a62', '#b2182b']
cmap = LinearSegmentedColormap.from_list('BlueRed', 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.20, 0.08, 0.50, 0.60])
ax_col_dend = fig.add_axes([0.20, 0.70, 0.50, 0.12])
ax_row_dend = fig.add_axes([0.04, 0.08, 0.15, 0.60])
ax_cbar = fig.add_axes([0.88, 0.25, 0.025, 0.25])
# Heatmap
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(n_rows))
ax_heatmap.set_yticklabels([f'Otu{i:05d}' for i in row_order], fontsize=6)
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')
# Column dendrogram
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')
# Row dendrogram
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')
# Colorbar
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
☕