Skip to content

colormaps module

Module for commonly used colormaps and palettes for visualizing geospatial data.

create_colormap(cmap='gray', colors=None, discrete=False, label=None, width=8.0, height=0.4, orientation='horizontal', vmin=0, vmax=1.0, axis_off=False, show_name=False, font_size=12, **kwargs)

Plot a matplotlib colormap.

Parameters:

Name Type Description Default
cmap str

Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.

'gray'
colors list

A list of custom colors to create a colormap. Defaults to None.

None
discrete bool

Whether to create a discrete colorbar. Defaults to False.

False
label str

Label for the colorbar. Defaults to None.

None
width float

The width of the colormap. Defaults to 8.0.

8.0
height float

The height of the colormap. Defaults to 0.4.

0.4
orientation str

The orientation of the colormap. Defaults to "horizontal".

'horizontal'
vmin float

The minimum value range. Defaults to 0.

0
vmax float

The maximum value range. Defaults to 1.0.

1.0
axis_off bool

Whether to turn axis off. Defaults to False.

False
show_name bool

Whether to show the colormap name. Defaults to False.

False
font_size int

Font size of the text. Defaults to 12.

12
Source code in leafmap/colormaps.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def create_colormap(
    cmap: Optional[str] = "gray",
    colors: Optional[List] = None,
    discrete: Optional[bool] = False,
    label: Optional[str] = None,
    width: Optional[float] = 8.0,
    height: Optional[float] = 0.4,
    orientation: Optional[str] = "horizontal",
    vmin: Optional[float] = 0,
    vmax: Optional[float] = 1.0,
    axis_off: Optional[bool] = False,
    show_name: Optional[bool] = False,
    font_size: Optional[int] = 12,
    **kwargs,
) -> None:
    """Plot a matplotlib colormap.

    Args:
        cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
        colors (list, optional): A list of custom colors to create a colormap. Defaults to None.
        discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
        label (str, optional): Label for the colorbar. Defaults to None.
        width (float, optional): The width of the colormap. Defaults to 8.0.
        height (float, optional): The height of the colormap. Defaults to 0.4.
        orientation (str, optional): The orientation of the colormap. Defaults to "horizontal".
        vmin (float, optional): The minimum value range. Defaults to 0.
        vmax (float, optional): The maximum value range. Defaults to 1.0.
        axis_off (bool, optional): Whether to turn axis off. Defaults to False.
        show_name (bool, optional): Whether to show the colormap name. Defaults to False.
        font_size (int, optional): Font size of the text. Defaults to 12.
    """
    fig, ax = plt.subplots(figsize=(width, height))

    if colors is not None and (isinstance(colors, list) or isinstance(colors, tuple)):
        hexcodes = to_hex_colors(list(colors))
        if discrete:
            col_map = mpl.colors.ListedColormap(hexcodes)
            vals = np.linspace(vmin, vmax, col_map.N + 1)
            norm = mpl.colors.BoundaryNorm(vals, col_map.N)

        else:
            col_map = mpl.colors.LinearSegmentedColormap.from_list(
                "custom", hexcodes, N=256
            )
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
    else:
        col_map = mpl.colormaps[cmap]
        norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    cb = mpl.colorbar.ColorbarBase(
        ax, norm=norm, cmap=col_map, orientation=orientation, **kwargs
    )

    if label is not None and isinstance(label, str):
        cb.set_label(label, fontsize=font_size)

    if axis_off:
        ax.set_axis_off()
    ax.tick_params(labelsize=font_size)

    if show_name:
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, cmap, va="center", ha="right", fontsize=font_size)

    return fig

get_colorbar(colors, vmin=0, vmax=1, width=6.0, height=0.4, orientation='horizontal', discrete=False)

Creates a colorbar based on custom colors.

Parameters:

Name Type Description Default
colors list

A list of hex colors.

required
vmin float

The minimum value range. Defaults to 0.

0
vmax float

The maximum value range. Defaults to 1.0.

1
width float

The width of the colormap. Defaults to 6.0.

6.0
height float

The height of the colormap. Defaults to 0.4.

0.4
orientation str

The orientation of the colormap. Defaults to "horizontal".

'horizontal'
discrete bool

Whether to create a discrete colormap.

False
Source code in leafmap/colormaps.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def get_colorbar(
    colors: List,
    vmin: Optional[float] = 0,
    vmax: Optional[float] = 1,
    width: Optional[float] = 6.0,
    height: Optional[float] = 0.4,
    orientation: Optional[str] = "horizontal",
    discrete: Optional[bool] = False,
) -> None:
    """Creates a colorbar based on custom colors.

    Args:
        colors (list): A list of hex colors.
        vmin (float, optional): The minimum value range. Defaults to 0.
        vmax (float, optional): The maximum value range. Defaults to 1.0.
        width (float, optional): The width of the colormap. Defaults to 6.0.
        height (float, optional): The height of the colormap. Defaults to 0.4.
        orientation (str, optional): The orientation of the colormap. Defaults to "horizontal".
        discrete (bool, optional): Whether to create a discrete colormap.
    """
    hexcodes = [i if i[0] == "#" else "#" + i for i in colors]
    _, ax = plt.subplots(figsize=(width, height))
    if discrete:
        cmap = mpl.colors.ListedColormap(hexcodes)
        vals = np.linspace(vmin, vmax, cmap.N + 1)
        norm = mpl.colors.BoundaryNorm(vals, cmap.N)
    else:
        cmap = mpl.colors.LinearSegmentedColormap.from_list("custom", hexcodes, N=256)
        norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
    mpl.colorbar.ColorbarBase(ax, norm=norm, cmap=cmap, orientation=orientation)
    plt.show()

get_palette(cmap_name=None, n_class=None, hashtag=False)

Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

Parameters:

Name Type Description Default
cmap_name str

The name of the matplotlib colormap. Defaults to None.

None
n_class int

The number of colors. Defaults to None.

None
hashtag bool

Whether to return a list of hex colors. Defaults to False.

False

Returns:

Name Type Description
list List[str]

A list of hex colors.

Source code in leafmap/colormaps.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def get_palette(
    cmap_name: Optional[str] = None,
    n_class: Optional[int] = None,
    hashtag: Optional[bool] = False,
) -> List[str]:
    """Get a palette from a matplotlib colormap. See the list of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

    Args:
        cmap_name (str, optional): The name of the matplotlib colormap. Defaults to None.
        n_class (int, optional): The number of colors. Defaults to None.
        hashtag (bool, optional): Whether to return a list of hex colors. Defaults to False.

    Returns:
        list: A list of hex colors.
    """

    if cmap_name in ["dem", "ndvi", "ndwi"]:
        colors = _palette_dict[cmap_name]
    else:
        cmap = mpl.colormaps[cmap_name]  # Retrieve colormap
        if n_class:
            colors = [
                mpl.colors.rgb2hex(cmap(i / (n_class - 1)))[1:] for i in range(n_class)
            ]
        else:
            colors = [mpl.colors.rgb2hex(cmap(i))[1:] for i in range(cmap.N)]
    if hashtag:
        colors = ["#" + i for i in colors]
    return colors

list_colormaps(add_extra=False, lowercase=False)

List all available colormaps. See a complete lost of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

Parameters:

Name Type Description Default
add_extra bool

If True, include additional colormaps, Default False,

False
lowercase bool

If True, convert colormaps names to lowercase, Default is False.

False

Returns:

Name Type Description
list List

The list of colormap names.

Source code in leafmap/colormaps.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def list_colormaps(add_extra: bool = False, lowercase: bool = False) -> List:
    """List all available colormaps. See a complete lost of colormaps at https://matplotlib.org/stable/tutorials/colors/colormaps.html.

    Args:
        add_extra (bool, optional): If True, include additional colormaps, Default False,
        lowercase (bool, optional): If True, convert colormaps names to lowercase, Default is False.

    Returns:
        list: The list of colormap names.
    """
    result = plt.colormaps()
    if add_extra:
        result += ["dem", "ndvi", "ndwi"]
    if lowercase:
        result = [i.lower() for i in result]
    result.sort()
    return result

plot_colormap(cmap='gray', colors=None, discrete=False, label=None, width=8.0, height=0.4, orientation='horizontal', vmin=0, vmax=1.0, axis_off=False, show_name=False, font_size=12, **kwargs)

Plot a matplotlib colormap.

Parameters:

Name Type Description Default
cmap str

Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.

'gray'
colors list

A list of custom colors to create a colormap. Defaults to None.

None
discrete bool

Whether to create a discrete colorbar. Defaults to False.

False
label str

Label for the colorbar. Defaults to None.

None
width float

The width of the colormap. Defaults to 8.0.

8.0
height float

The height of the colormap. Defaults to 0.4.

0.4
orientation str

The orientation of the colormap. Defaults to "horizontal".

'horizontal'
vmin float

The minimum value range. Defaults to 0.

0
vmax float

The maximum value range. Defaults to 1.0.

1.0
axis_off bool

Whether to turn axis off. Defaults to False.

False
show_name bool

Whether to show the colormap name. Defaults to False.

False
font_size int

Font size of the text. Defaults to 12.

12
Source code in leafmap/colormaps.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def plot_colormap(
    cmap: Optional[str] = "gray",
    colors: Optional[List] = None,
    discrete: Optional[bool] = False,
    label: Optional[str] = None,
    width: Optional[float] = 8.0,
    height: Optional[float] = 0.4,
    orientation: Optional[str] = "horizontal",
    vmin: Optional[float] = 0,
    vmax: Optional[float] = 1.0,
    axis_off: Optional[bool] = False,
    show_name: Optional[bool] = False,
    font_size: Optional[int] = 12,
    **kwargs,
) -> None:
    """Plot a matplotlib colormap.

    Args:
        cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
        colors (list, optional): A list of custom colors to create a colormap. Defaults to None.
        discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
        label (str, optional): Label for the colorbar. Defaults to None.
        width (float, optional): The width of the colormap. Defaults to 8.0.
        height (float, optional): The height of the colormap. Defaults to 0.4.
        orientation (str, optional): The orientation of the colormap. Defaults to "horizontal".
        vmin (float, optional): The minimum value range. Defaults to 0.
        vmax (float, optional): The maximum value range. Defaults to 1.0.
        axis_off (bool, optional): Whether to turn axis off. Defaults to False.
        show_name (bool, optional): Whether to show the colormap name. Defaults to False.
        font_size (int, optional): Font size of the text. Defaults to 12.
    """
    fig, ax = plt.subplots(figsize=(width, height))

    if colors is not None and (isinstance(colors, list) or isinstance(colors, tuple)):
        hexcodes = to_hex_colors(list(colors))
        if discrete:
            col_map = mpl.colors.ListedColormap(hexcodes)
            vals = np.linspace(vmin, vmax, col_map.N + 1)
            norm = mpl.colors.BoundaryNorm(vals, col_map.N)

        else:
            col_map = mpl.colors.LinearSegmentedColormap.from_list(
                "custom", hexcodes, N=256
            )
            norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
    else:
        col_map = mpl.colormaps[cmap]
        norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    cb = mpl.colorbar.ColorbarBase(
        ax, norm=norm, cmap=col_map, orientation=orientation, **kwargs
    )

    if label is not None and isinstance(label, str):
        cb.set_label(label, fontsize=font_size)

    if axis_off:
        ax.set_axis_off()
    ax.tick_params(labelsize=font_size)

    if show_name:
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, cmap, va="center", ha="right", fontsize=font_size)

    plt.show()

plot_colormaps(width=8.0, height=0.4, return_fig=False, **kwargs)

Plot all available colormaps.

Parameters:

Name Type Description Default
width float

Width of the colormap. Defaults to 8.0.

8.0
height float

Height of the colormap. Defaults to 0.4.

0.4
return_fig bool

Whether to return the figure. Defaults to False.

False
Source code in leafmap/colormaps.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def plot_colormaps(
    width: Optional[float] = 8.0,
    height: Optional[float] = 0.4,
    return_fig: Optional[bool] = False,
    **kwargs,
) -> None:
    """Plot all available colormaps.

    Args:
        width (float, optional): Width of the colormap. Defaults to 8.0.
        height (float, optional): Height of the colormap. Defaults to 0.4.
        return_fig (bool, optional): Whether to return the figure. Defaults to False.
    """
    cmap_list = list_colormaps()
    nrows = len(cmap_list)
    fig, axes = plt.subplots(nrows=nrows, figsize=(width, height * nrows))
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)

    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))

    for ax, name in zip(axes, cmap_list):
        ax.imshow(gradient, aspect="auto", cmap=mpl.colormaps[name])
        ax.set_axis_off()
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, name, va="center", ha="right", fontsize=12)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axes:
        ax.set_axis_off()

    if return_fig:
        return fig
    else:
        plt.show()