62 folium colorbar
import leafmap.foliumap as leafmap
Unlike the ipyleaflet plotting backend, folium does not support adding matplotlib colormap directly. One workaround is to save the maplotlib colormap as an image, then add the image to the map. Let's first create a colormap.
Create a colormap using specified parameters.
params = {
"width": 4.0,
"height": 0.3,
"vmin": 0,
"vmax": 6000,
"cmap": "terrain",
"label": "Elevation (m)",
"orientation": "horizontal",
"transparent": False,
}
Save the colormap as an image.
leafmap.save_colorbar("colorbar.png", **params)
'/home/runner/work/leafmap/leafmap/docs/notebooks/colorbar.png'
You can also create use the m.add_colormap()
method to add a colormap. Under the hood, it generate a colormap as an image, then add it to the map. You need to specified the position of the colormap using a tuple (x, y), which represents the percentage [0-100] from the lower-left corner. If the map size changes, you might need to change the colormap position as well.
Add a horizontal colormap to the map.
m = leafmap.Map()
m.add_basemap("OpenTopoMap")
m.add_colormap(position=(55, 5), **params)
m
Make the colormap background transparent.
params["transparent"] = True
m = leafmap.Map()
m.add_basemap("OpenTopoMap")
m.add_colormap(position=(55, 5), **params)
m
Change the orientation to vertical.
params = {
"width": 0.3,
"height": 4,
"vmin": 0,
"vmax": 6000,
"cmap": "terrain",
"label": "Elevation (m)",
"orientation": "vertical",
"transparent": False,
}
m = leafmap.Map()
m.add_basemap("OpenTopoMap")
m.add_colormap(position=(85, 5), **params)
m
To make the colormap position fixed at four corners (i.e., bottomright
, bottomleft
, topright
, topleft
), you need to make the image available through an HTTP URL (e.g., imgur). Local file paths are not supported. Use m.add_image()
to add the colormap image to the map.
m = leafmap.Map()
m.add_basemap("OpenTopoMap")
image = "https://i.imgur.com/SpmE7Cs.png"
m.add_image(image, position="bottomright")
m