Visualize Hi-C contact matrices, TADs, loops, and genomic features using matplotlib, cooltools, and HiCExplorer. Create triangle plots, virtual 4C, and multi-track figures. Use when visualizing contact matrices or genomic features.
Before using code patterns, verify installed versions match. If versions differ:
Python: pip show <package> then help(module.function) to check signatures
CLI: <tool> --version then <tool> --help to confirm flags
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
Hi-C Visualization
"Plot my Hi-C contact matrix" → Create triangle heatmaps, virtual 4C profiles, and multi-track figures combining contact maps with genomic annotations.
Python: matplotlib.pyplot.imshow() on cooler matrices, cooltools for aggregate plots
CLI: hicPlotMatrix (HiCExplorer)
Visualize Hi-C contact matrices and genomic features.
Required Imports
import cooler
import cooltools
import cooltools.lib.plotting
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import bioframe
Basic Contact Matrix Plot
clr = cooler.Cooler('matrix.mcool::resolutions/10000')
# Get matrix for a region
matrix = clr.matrix(balance=True).fetch('chr1:50000000-60000000')
fig, ax = plt.subplots(figsize=(8, 8))
im = ax.imshow(matrix, cmap='Reds', norm=LogNorm(vmin=0.001, vmax=0.1))
plt.colorbar(im, ax=ax, label='Balanced contacts')
ax.set_title('chr1:50-60Mb')
plt.savefig('contact_matrix.png', dpi=150)
Triangle (Upper Triangle) Plot
def plot_triangle(matrix, ax, cmap='Reds', vmin=None, vmax=None):
'''Plot Hi-C matrix as triangle (rotated 45 degrees)'''
n = matrix.shape[0]
# Create rotated matrix
rotated = np.zeros((n, 2*n))
for i in range(n):
for j in range(i, n):
y = j - i
x = i + j
rotated[y, x] = matrix[i, j]
# Plot
im = ax.imshow(rotated[:n//2, :], cmap=cmap, aspect='auto',
norm=LogNorm(vmin=vmin, vmax=vmax) if vmin else None)
ax.set_ylim(n//2, 0)
return im
matrix = clr.matrix(balance=True).fetch('chr1:50000000-60000000')
fig, ax = plt.subplots(figsize=(12, 4))
im = plot_triangle(matrix, ax, vmin=0.001, vmax=0.1)
plt.colorbar(im, ax=ax)
plt.savefig('triangle_plot.png', dpi=150)
Plot with TADs
import pandas as pd
matrix = clr.matrix(balance=True).fetch('chr1:50000000-60000000')
tads = pd.read_csv('tads.bed', sep='\t', names=['chrom', 'start', 'end'])
fig, ax = plt.subplots(figsize=(8, 8))
im = ax.imshow(matrix, cmap='Reds', norm=LogNorm(vmin=0.001, vmax=0.1))
# Overlay TAD boundaries
region_start = 50000000
bin_size = clr.binsize
for _, tad in tads[tads['chrom'] == 'chr1'].iterrows():
if region_start <= tad['start'] < 60000000:
pos = (tad['start'] - region_start) / bin_size
ax.axhline(pos, color='blue', linewidth=0.5, alpha=0.5)
ax.axvline(pos, color='blue', linewidth=0.5, alpha=0.5)
plt.colorbar(im, ax=ax)
plt.savefig('matrix_with_tads.png', dpi=150)
Plot with Loops
matrix = clr.matrix(balance=True).fetch('chr1:50000000-60000000')
loops = pd.read_csv('loops.bedpe', sep='\t')
fig, ax = plt.subplots(figsize=(8, 8))
im = ax.imshow(matrix, cmap='Reds', norm=LogNorm(vmin=0.001, vmax=0.1))
# Mark loops
region_start = 50000000
bin_size = clr.binsize
for _, loop in loops[loops['chrom1'] == 'chr1'].iterrows():
if (region_start <= loop['start1'] < 60000000 and
region_start <= loop['start2'] < 60000000):
x = (loop['start1'] - region_start) / bin_size
y = (loop['start2'] - region_start) / bin_size
circle = plt.Circle((y, x), 3, fill=False, color='blue', linewidth=1)
ax.add_patch(circle)
plt.colorbar(im, ax=ax)
plt.savefig('matrix_with_loops.png', dpi=150)
Goal: Extract a one-dimensional contact frequency profile from a single viewpoint locus, simulating a 4C experiment from Hi-C data.
Approach: Select the matrix row corresponding to the viewpoint bin, extract balanced contact values across the chromosome, and plot as a filled line graph.
def virtual_4c(clr, viewpoint_chrom, viewpoint_pos, resolution=10000):
'''Extract virtual 4C from Hi-C'''
# Get row of matrix at viewpoint
viewpoint_bin = viewpoint_pos // resolution
# Get contacts from this bin to all others on same chromosome
matrix = clr.matrix(balance=True).fetch(viewpoint_chrom)
v4c = matrix[viewpoint_bin, :]
# Create coordinates
bins = clr.bins().fetch(viewpoint_chrom)
coords = bins['start'].values
return coords, v4c
coords, v4c = virtual_4c(clr, 'chr1', 55000000)
fig, ax = plt.subplots(figsize=(12, 3))
ax.fill_between(coords / 1e6, 0, v4c, alpha=0.5)
ax.axvline(55, color='red', linestyle='--', label='Viewpoint')
ax.set_xlabel('Position (Mb)')
ax.set_ylabel('Contact frequency')
ax.set_title('Virtual 4C from chr1:55Mb')
ax.legend()
plt.savefig('virtual_4c.png', dpi=150)