How to add a background color of a colormap in a folium map

Viewed 1600

I am working with folium maps created based on json files. I added a colormap using branca.colormap and I want to add a background color since the resulting colormap can have some colors with the map behind it and that will cause a visualization problem.

Can I add this colormap to a frame or just add a background color?

2 Answers

This is a rather hacky solution, but it works:

Open the html-file generated by folium, by the function map_instance.save('map.html').

Look for the line generating the leaflet-control, by searching for .append("svg")

Insert this code snippet after it, making sure to get the variable name correct (i.e. copy the random generated id from the variable in your code)

color_map_<random_generated_id>.svg.append("rect")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr("fill", "white")
    .attr("opacity", "0.8");

You can also position the legend by changing the leaflet-control position attribute in the color_map_<random_generated_id>.legend variable. In my example I use L.control({position: 'bottomleft'});

Image example

Branca colourmap is created as an SVG object. So, if you add a style in the CSS specifically asking for the SVG to have a background, then your colourmap will have a background. Sorry for giving an answer in a different programming language (python), but you will get the gist.

Methods 1

import folium
import branca.colormap as cm

m = folium.Map(tiles="cartodbpositron")

colormap = cm.linear.Set1_09.scale(0, 35).to_step(10)
colormap.caption = "A colormap caption"
svg_style = '<style>svg {background-color: white;}</style>'

m.get_root().header.add_child(folium.Element(svg_style))
colormap.add_to(m)

m

Method 2 (ugly)

m = folium.Map(tiles="cartodbpositron")

colormap = cm.linear.Set1_09.scale(0, 35).to_step(100)
colormap.caption = "A colormap caption"
cmap_HTML = colormap._repr_html_()
cmap_HTML = cmap_HTML.replace('<svg height="50" width="500">','<svg id="cmap" height="50" width="500">',1)
cmap_style = '<style>#cmap {background-color: green;}</style>'

m.get_root().header.add_child(folium.Element(cmap_style))
folium.map.LayerControl().add_to(m)
m.get_root().html.add_child(folium.Element(cmap_HTML))

m
Related