简体   繁体   中英

How to add legend/gradient in Folium Heat Map?

I am creating a heat map using Folium.My data contains 3 columns one is category, lat and long. The lat-long points are categorized into 3 categories like A, B, and C. I am able to plot the heat map using folium, but I need to add the legend showing the color difference between the points.I need to mark points into 3 different colors based on the category.

I am attaching the sample code which for your reference.Any help is appreciated.

Thanks in advance!

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')

Below is the solution and it's based on the answer of @Alexei Novikov Code below is more complete

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

You have to create a dictionary with colormap values

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)

and then use it as the gradient for the HeatMap.

HeatMap(heat_data, gradient = gradient_map)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM