如何在folium地图中添加一个colormap的背景颜色

4

我正在处理基于json文件创建的folium地图。我使用branca.colormap添加了一个colormap,并且我想添加一个背景色,因为结果图中的一些颜色会与地图背景产生冲突,从而导致可视化问题。

我可以将此colormap添加到框架中,或者只是添加背景颜色吗?

2个回答

5

这是一种比较巧妙的解决方案,但它可以工作:

通过folium生成的html文件打开,方法是使用函数map_instance.save('map.html')

查找生成leaflet控件的行,方法是搜索.append("svg")

在此之后插入此代码片段,确保正确获取变量名(即从代码中复制随机生成的id)

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

您可以通过更改 color_map_<random_generated_id>.legend 变量中的 leaflet-control 位置属性来定位图例。在我的示例中,我使用 L.control({position:'bottomleft'});

图像示例


在上面的代码中添加 .attr("rx", 5).attr("ry", 5) 来获得圆角。 :) - ACR

1
Branca色彩地图是创建为SVG对象。因此,如果你在CSS中添加一个样式,特别要求SVG具有背景,则你的色彩地图将具有背景。很抱歉以一种不同的编程语言(Python)给出答案,但你会明白的。
方法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

方法二(不太美观)

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

第一种方法效果不错。但是,如何确保它只影响颜色映射?我发现它还会影响添加的GeoJson图层。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接