Folium 允許使用工具提示或彈出文本創建標記。我想對我的 GeoJSON 多邊形做同樣的事情。
我的 GeoJSON 有一個名為"name"( feature.properties.name-> 假設它是美國每個州的名稱)的屬性。除了每個州的失業率之外,我還希望能夠將其顯示為我的等值分布圖中的標簽。我在"State"來自pandas dataframe.
這可能嗎?我會很高興有一個解決方案,它允許它成為彈出視窗、工具提示或寫在頂部的簡單文本標簽。
import pandas as pd
url = (
"https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
m = folium.Map(location=[48, -102], zoom_start=3)
folium.Choropleth(
geo_data=state_geo,
name="choropleth",
data=state_data,
columns=["State", "Unemployment"],
key_on="feature.id",
fill_color="YlGn",
fill_opacity=0.7,
line_opacity=0.2,
legend_name="Unemployment Rate (%)",
).add_to(m)
folium.LayerControl().add_to(m)
m
uj5u.com熱心網友回復:
過去,我不得不使用 folium 的 GeoJsonTooltip() 和其他一些步驟來完成這項作業。我很想知道是否有人有更好的方法
- 捕獲 Choropleth 函式的回傳值
- 向 Chopleth 的底層 geojson obj 添加一個值(例如失業)
- 使用步驟 2 中的值創建 GeoJsonTooltip
- 將該工具提示添加到 choropleth 的 geojson
url = (
"https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"
state_unemployment = f"{url}/US_Unemployment_Oct2012.csv"
state_data = pd.read_csv(state_unemployment)
m = folium.Map(location=[48, -102], zoom_start=3)
# capturing the return of folium.Choropleth()
cp = folium.Choropleth(
geo_data=state_geo,
name="choropleth",
data=state_data,
columns=["State", "Unemployment"],
key_on="feature.id",
fill_color="YlGn",
fill_opacity=0.7,
line_opacity=0.2,
legend_name="Unemployment Rate (%)",
).add_to(m)
# creating a state indexed version of the dataframe so we can lookup values
state_data_indexed = state_data.set_index('State')
# looping thru the geojson object and adding a new property(unemployment)
# and assigning a value from our dataframe
for s in cp.geojson.data['features']:
s['properties']['unemployment'] = state_data_indexed.loc[s['id'], 'Unemployment']
# and finally adding a tooltip/hover to the choropleth's geojson
folium.GeoJsonTooltip(['name', 'unemployment']).add_to(cp.geojson)
folium.LayerControl().add_to(m)
m

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/392888.html
