如何在Folium热力图中添加图例/渐变?

4
我正在使用Folium创建热力图。我的数据包含3列,分别是类别、纬度和经度。纬度和经度点被分为A、B、C三种类别。 我能够使用folium绘制热力图,但我需要添加图例以显示点之间的颜色差异。我需要根据类别将点标记为3种不同的颜色。
以下是一个示例代码,供您参考。感谢您提供的任何帮助。
谢谢!
from folium import plugins
from folium.plugins import HeatMap
from folium.plugins import MarkerCluster
import pandas as pd

map = folium.Map(location=[lat, long],zoom_start =12) 
data = pd.read_csv(filename)
# List comprehension to make out list of lists
heat_data = [[row['LAT'],row['LONG'],] for index, row in data.iterrows()]
# Plot it on the map
HeatMap(heat_data).add_to(map)
# Display the map
map
map.save('C:\Temp\map2.html')
2个回答

8
以下是解决方案,它基于@Alexei Novikov的答案。下面的代码更加完整。
import branca.colormap
from collections import defaultdict
import folium
import webbrowser
from folium.plugins import HeatMap 

map_osm = folium.Map(llocation=[35,110],zoom_start=1)

steps=20
colormap = branca.colormap.linear.YlOrRd_09.scale(0, 1).to_step(steps)
gradient_map=defaultdict(dict)
for i in range(steps):
    gradient_map[1/steps*i] = colormap.rgb_hex_str(1/steps*i)
colormap.add_to(map_osm) #add color bar at the top of the map

HeatMap(data1,gradient = gradient_map).add_to(map_osm) # Add heat map to the previously created map

file_path = r"C:\\test.html"
map_osm.save(file_path) # Save as html file
webbrowser.open(file_path) # Default browser open

5
你需要创建一个带有颜色映射值的字典。
steps = 20
color_map=cm.linear.PuBu.scale(0,1).to_step(steps)

gradient_map=defaultdict(dict)
for i in range(steps):
    gradient_map[1/steps*i] = color_map.rgb_hex_str(1/steps*i)

然后将其用作热力图的渐变色。

HeatMap(heat_data, gradient = gradient_map)

definite defaultdict(dict) 是什么意思? - user1345283
在这种情况下,“cm”等于多少? - NL23codes
刚刚想到了:import branca.colormap as cm - NL23codes

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