Line data Source code
1 : # SPDX-FileCopyrightText: 2025 PairInteraction Developers
2 : # SPDX-License-Identifier: LGPL-3.0-or-later
3 1 : from __future__ import annotations
4 :
5 1 : from typing import TYPE_CHECKING
6 :
7 1 : import matplotlib.pyplot as plt
8 1 : import numpy as np
9 1 : from matplotlib.colors import ListedColormap
10 :
11 : if TYPE_CHECKING:
12 : from matplotlib import colors
13 :
14 :
15 1 : def _colormap_add_transparency(cmap: colors.Colormap, min_value: float = 1e-4) -> colors.ListedColormap:
16 : """Add transparency to a colormap.
17 :
18 : This function returns a copy of the given colormap to include an alpha channel
19 : that represents transparency based on the specified minimum overlap.
20 :
21 : Args:
22 : cmap: The colormap to modify.
23 : min_value: Reference value, at which the alpha channel should be 0.
24 : This also shifts the alpha channel for larger values.
25 : Defaults to 1e-4.
26 :
27 : Returns:
28 : A ListedColormap with transparency applied.
29 :
30 : """
31 1 : cmap_with_alpha = cmap(np.arange(cmap.N))
32 :
33 1 : values = np.linspace(0, 1, cmap.N)
34 1 : alpha = 1 - np.log(values[1:]) / np.log(min_value)
35 1 : cmap_with_alpha[0, -1] = 0
36 1 : cmap_with_alpha[1:, -1] = np.clip(alpha, 0, 1)
37 :
38 1 : return ListedColormap(cmap_with_alpha)
39 :
40 :
41 1 : alphamagma = _colormap_add_transparency(plt.get_cmap("magma_r"), min_value=1e-4)
|