如何使用 Folium 将聚类标记添加到 Choropleth

How to add Cluster markers to Choropleth with Folium

我已经在 Folium 中使用 Choropleth 和 Cluster 标记地图工作了一段时间(很棒)。我的问题是是否可以将它们组合在一张地图中,这样我就可以看到一个变量对另一个变量的影响有多大。我可以让两种地图类型单独工作,所以没有问题。到目前为止,这是我尝试将两者结合起来的代码:

import pandas as pd
import folium
from folium.plugins import MarkerCluster

input_filename="input_filename.csv"
df = pd.read_csv(input_filename,encoding='utf8')
geo = 'blah.json'
comparison = 'comparison.csv'
comparison_data = pd.read_csv(comparison)

m = folium.Map(location=[Lat,Lon], zoom_start=12)

folium.Choropleth(
    geo_data=geo,
    name='choropleth',
    data=comparison_data,
    columns=['col1','col2'],
    key_on='feature.properties.ID',
    fill_color='OrRd',
    fill_opacity=0.5,
    line_opacity=0.5,
    legend_name='Blah (%)'
).add_to(m)

folium.LayerControl().add_to(m)
marker_cluster = MarkerCluster().add_to(m)

for row in df.itertuples():
    folium.Marker(location=[row.Lat,row.Lon],popup=row.Postcode).add_to(marker_cluster)

m

它会生成等值线,但不会对聚类标记进行分层。值得注意的是,我在 Jupyter notebook 中无法单独显示聚类标记时遇到了问题,但我通过将文件另存为 html 来解决这个问题,然后就可以看到了。

好的,我已经解决了,真的很高兴!!解决方案是先做标记簇,然后再做 Choropleth:

import pandas as pd
import folium
from folium.plugins import MarkerCluster

m = folium.Map(location=[Lat,Lon], zoom_start=12)

input_filename="input_filename.csv"
df = pd.read_csv(input_filename,encoding='utf8')
geo = 'blah.json'
comparison = 'comparison.csv'
comparison_data = pd.read_csv(comparison)

folium.LayerControl().add_to(m)
marker_cluster = MarkerCluster().add_to(m)

for row in df.itertuples():
    folium.Marker(location=[row.Lat,row.Lon],popup=row.Postcode).add_to(marker_cluster)

folium.Choropleth(
    geo_data=geo,
    name='choropleth',
    data=comparison_data,
    columns=['col1','col2'],
    key_on='feature.properties.ID',
    fill_color='OrRd',
    fill_opacity=0.5,
    line_opacity=0.5,
    legend_name='Blah (%)'
).add_to(m)

m
from random import randint
import folium

def rgb_to_hex(rgb):
    return '#%02x%02x%02x' % rgb

mp = folium.Map(location=[40.6, -73.7], scale = 10)

colors = []
while len(colors) != 50:
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)
    if rgb_to_hex((r, g, b)) not in colors:
        colors.append(rgb_to_hex((r, g, b)))
        
for j in range(df.shape[0]):
    lat = df.iloc[j]['latitude']
    lon = df.iloc[j]['longitude']
    color = colors[int(df.iloc[j]['clust'])]
    
    folium.Circle(location=[lat, lon], radius=8, color = color).add_to(mp)