Create a `LinearSegmentedColormap` from a list of colors. Parameters ---------- name : str The name of the colormap. colors : list of :mpltype:`color` or list of (value, color) If only colors are given, they are equidistantly mapped f
(name, colors, N=256, gamma=1.0, *, bad=None, under=None, over=None)
| 1184 | |
| 1185 | @staticmethod |
| 1186 | def from_list(name, colors, N=256, gamma=1.0, *, bad=None, under=None, over=None): |
| 1187 | """ |
| 1188 | Create a `LinearSegmentedColormap` from a list of colors. |
| 1189 | |
| 1190 | Parameters |
| 1191 | ---------- |
| 1192 | name : str |
| 1193 | The name of the colormap. |
| 1194 | colors : list of :mpltype:`color` or list of (value, color) |
| 1195 | If only colors are given, they are equidistantly mapped from the |
| 1196 | range :math:`[0, 1]`; i.e. 0 maps to ``colors[0]`` and 1 maps to |
| 1197 | ``colors[-1]``. |
| 1198 | If (value, color) pairs are given, the mapping is from *value* |
| 1199 | to *color*. This can be used to divide the range unevenly. The |
| 1200 | values must increase monotonically from 0 to 1. |
| 1201 | N : int |
| 1202 | The number of RGB quantization levels. |
| 1203 | gamma : float |
| 1204 | |
| 1205 | bad : :mpltype:`color`, default: transparent |
| 1206 | The color for invalid values (NaN or masked). |
| 1207 | under : :mpltype:`color`, default: color of the lowest value |
| 1208 | The color for low out-of-range values. |
| 1209 | over : :mpltype:`color`, default: color of the highest value |
| 1210 | The color for high out-of-range values. |
| 1211 | """ |
| 1212 | if not np.iterable(colors): |
| 1213 | raise ValueError('colors must be iterable') |
| 1214 | |
| 1215 | try: |
| 1216 | # Assume the passed colors are a list of colors |
| 1217 | # and not a (value, color) tuple. |
| 1218 | r, g, b, a = to_rgba_array(colors).T |
| 1219 | vals = np.linspace(0, 1, len(colors)) |
| 1220 | except Exception as e: |
| 1221 | # Assume the passed values are a list of |
| 1222 | # (value, color) tuples. |
| 1223 | try: |
| 1224 | _vals, _colors = itertools.zip_longest(*colors) |
| 1225 | except Exception as e2: |
| 1226 | raise e2 from e |
| 1227 | vals = np.asarray(_vals) |
| 1228 | if np.min(vals) < 0 or np.max(vals) > 1 or np.any(np.diff(vals) <= 0): |
| 1229 | raise ValueError( |
| 1230 | "the values passed in the (value, color) pairs " |
| 1231 | "must increase monotonically from 0 to 1." |
| 1232 | ) |
| 1233 | r, g, b, a = to_rgba_array(_colors).T |
| 1234 | |
| 1235 | cdict = { |
| 1236 | "red": np.column_stack([vals, r, r]), |
| 1237 | "green": np.column_stack([vals, g, g]), |
| 1238 | "blue": np.column_stack([vals, b, b]), |
| 1239 | "alpha": np.column_stack([vals, a, a]), |
| 1240 | } |
| 1241 | |
| 1242 | return LinearSegmentedColormap(name, cdict, N, gamma, |
| 1243 | bad=bad, under=under, over=over) |