|
| 1 | +import numpy as np |
| 2 | +from matplotlib.colors import ListedColormap, to_rgb |
| 3 | +import matplotlib.tri as mtri |
| 4 | +from scipy.interpolate import griddata |
| 5 | +from scipy.ndimage import gaussian_filter |
| 6 | +from matplotlib.colors import to_hex |
| 7 | +import matplotlib.pyplot as plt |
| 8 | + |
| 9 | +def _smooth_contour( |
| 10 | + x: np.ndarray, |
| 11 | + y: np.ndarray, |
| 12 | + z: np.ndarray, |
| 13 | + levels: int = 6, |
| 14 | + grid_res: int = 200, |
| 15 | + smooth_sigma: float = 2, |
| 16 | + contour_kwargs: dict = None |
| 17 | +): |
| 18 | + """Overlay smooth contour lines by gridding + Gaussian blur. |
| 19 | +
|
| 20 | + Args: |
| 21 | + x, y: 1D arrays of spatial coordinates (length n_obs). |
| 22 | + z: 1D array of normalized or summarized expression (length n_obs). |
| 23 | + levels: Number of contour levels or list of levels. |
| 24 | + grid_res: Resolution of the regular grid along each axis. |
| 25 | + smooth_sigma: Sigma for Gaussian filter to smooth the gridded field. |
| 26 | + contour_kwargs: Extra kwargs passed to plt.contour (e.g. colors, linewidths). |
| 27 | +
|
| 28 | + Returns: |
| 29 | + The contour set drawn on the current axes. |
| 30 | + """ |
| 31 | + # 1) create regular grid |
| 32 | + xi = np.linspace(x.min(), x.max(), grid_res) |
| 33 | + yi = np.linspace(y.min(), y.max(), grid_res) |
| 34 | + Xi, Yi = np.meshgrid(xi, yi) |
| 35 | + |
| 36 | + # 2) interpolate scattered z onto the grid |
| 37 | + Zi = griddata((x, y), z, (Xi, Yi), method='cubic', fill_value=np.nan) |
| 38 | + |
| 39 | + # 3) smooth the gridded values |
| 40 | + Zi_s = gaussian_filter(Zi, sigma=smooth_sigma, mode='nearest') |
| 41 | + |
| 42 | + # 4) draw contours |
| 43 | + ctr_kw = {} if contour_kwargs is None else contour_kwargs |
| 44 | + cs = plt.contour(Xi, Yi, Zi_s, levels=levels, **ctr_kw) |
| 45 | + plt.clabel(cs, inline=True, fontsize=8) |
| 46 | + return cs |
| 47 | + |
| 48 | + |
| 49 | +def make_bivariate_cmap( |
| 50 | + c00: str = "#f0f0f0", |
| 51 | + c10: str = "#e31a1c", |
| 52 | + c01: str = "#1f78b4", |
| 53 | + c11: str = "#ffff00", |
| 54 | + n: int = 128 |
| 55 | +) -> ListedColormap: |
| 56 | + """Create a bivariate colormap by bilinear‐interpolating four corner colors. |
| 57 | +
|
| 58 | + This builds an (n × n) grid of RGB colors, blending smoothly between |
| 59 | + the specified corner colors: |
| 60 | + - c00 at (low, low) |
| 61 | + - c10 at (high, low) |
| 62 | + - c01 at (low, high) |
| 63 | + - c11 at (high, high) |
| 64 | + |
| 65 | + Args: |
| 66 | + c00: Matplotlib color spec (hex, name, or RGB tuple) for the low/low corner. |
| 67 | + c10: Color for the high/low corner. |
| 68 | + c01: Color for the low/high corner. |
| 69 | + c11: Color for the high/high corner. |
| 70 | + n: Resolution per axis. The total length of the returned colormap is n*n. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + ListedColormap: A colormap with n*n entries blending between the four corners. |
| 74 | + """ |
| 75 | + # Convert corner colors to RGB arrays |
| 76 | + corners = { |
| 77 | + (0, 0): np.array(to_rgb(c00)), |
| 78 | + (1, 0): np.array(to_rgb(c10)), |
| 79 | + (0, 1): np.array(to_rgb(c01)), |
| 80 | + (1, 1): np.array(to_rgb(c11)), |
| 81 | + } |
| 82 | + |
| 83 | + # Build an (n, n, 3) grid by bilinear interpolation |
| 84 | + lut = np.zeros((n, n, 3), dtype=float) |
| 85 | + xs = np.linspace(0, 1, n) |
| 86 | + ys = np.linspace(0, 1, n) |
| 87 | + for j, y in enumerate(ys): |
| 88 | + for i, x in enumerate(xs): |
| 89 | + lut[j, i] = ( |
| 90 | + corners[(0, 0)] * (1 - x) * (1 - y) + |
| 91 | + corners[(1, 0)] * x * (1 - y) + |
| 92 | + corners[(0, 1)] * (1 - x) * y + |
| 93 | + corners[(1, 1)] * x * y |
| 94 | + ) |
| 95 | + |
| 96 | + # Flatten to (n*n, 3) and return as a ListedColormap |
| 97 | + return ListedColormap(lut.reshape(n * n, 3)) |
0 commit comments