如何使用 Plotly Choropleth 在地图中添加静态文本 Python
How to add static text in map using Plotly Choropleth Python
我正在使用 plotly 和 geojson 文件绘制印度地图。现在我想做的是显示印度各州的静态值。目前这些值在悬停时可见,我希望这些值始终可见。
这是我的代码:
import pandas as pd
import plotly.graph_objects as go
df = data_state1
fig = go.Figure(data=go.Choropleth(
geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
featureidkey='properties.ST_NM',
locationmode='geojson-id',
locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
z=df['odval']/df['count'],
text= df['ST_NM'].str.title(),
autocolorscale=False,
colorscale='Reds',
marker_line_color='darkgreen',
colorbar=dict(
title={'text': "Amount"},
thickness=35,
len=1.0,
bgcolor='rgba(255,255,255,0.6)',
xanchor='right',
x=0.0,
yanchor='bottom',
y=0.0
),
))
fig.update_geos(
visible=True,
projection=dict(
type='conic conformal',
parallels=[12.472944444, 35.172805555556],
rotation={'lat': 24, 'lon': 80}
),
lonaxis={'range': [68, 98]},
lataxis={'range': [6, 38]}
)
fig.update_layout(
title=dict(
text="Average Overdue Amount over Total cases ",
xanchor='center',
x=0.5,
yref='paper',
yanchor='bottom',
y=0.9,
pad={'b': 0}
),
margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
height=850,
width=750
)
fig.show()
我也尝试过使用 geopandas,在该图上,我能够根据值绘制带有颜色的地图,但没有找到显示州名称和值的方法。
geopandas 的代码是:
fig, ax = plt.subplots(1, figsize=(10, 10))
ax.axis('off')
ax.set_title('ODVal/Cases distribution',
fontdict={'fontsize': '15', 'fontweight' : '3'})
merged.plot(column='ratio_od_cases',cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0', legend=True)
plt.text(,merged['State_Name'])
我认为在地图上添加文本最简单的方法是在 go.Scattergeo() 中使用文本模式并指定纬度和经度。从使用的geojson数据来看,geopandas用于计算文本显示的状态中心。
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from urllib import request
import json
url = "https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson"
with request.urlopen(url) as f:
geo_india = json.load(f)
import geopandas as gpd
df = gpd.read_file(url)
df["lon"] = df["geometry"].centroid.x
df["lat"] = df["geometry"].centroid.y
df['value'] = np.random.randint(5,50,36)
fig = go.Figure(data=go.Choropleth(
geojson=geo_india,
featureidkey='properties.ST_NM',
#locationmode='geojson-id',
locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
z=df['value'],
text= df['ST_NM'].str.title(),
autocolorscale=False,
colorscale='Reds',
marker_line_color='darkgreen',
colorbar=dict(
title={'text': "Amount"},
thickness=35,
len=1.0,
bgcolor='rgba(255,255,255,0.6)',
xanchor='right',
x=0.0,
yanchor='bottom',
y=0.0
),
))
fig.update_geos(
visible=True,
projection=dict(
type='conic conformal',
parallels=[12.472944444, 35.172805555556],
rotation={'lat': 24, 'lon': 80}
),
lonaxis={'range': [68, 98]},
lataxis={'range': [6, 38]}
)
fig.add_trace(go.Scattergeo(
lon=df['lon'],
lat=df['lat'],
mode='text',
#text=df['ST_NM'].str.title(),
text=['{}<br>{}'.format(k,v) for k,v in zip(df['ST_NM'].str.title(), df['value'])],
textfont={'color': 'Green'},
name='',
))
fig.update_layout(
title=dict(
text="Average Overdue Amount over Total cases ",
xanchor='center',
x=0.5,
yref='paper',
yanchor='bottom',
y=0.9,
pad={'b': 0}
),
margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
height=850,
width=750
)
fig.show()
我正在使用 plotly 和 geojson 文件绘制印度地图。现在我想做的是显示印度各州的静态值。目前这些值在悬停时可见,我希望这些值始终可见。
这是我的代码:
import pandas as pd
import plotly.graph_objects as go
df = data_state1
fig = go.Figure(data=go.Choropleth(
geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
featureidkey='properties.ST_NM',
locationmode='geojson-id',
locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
z=df['odval']/df['count'],
text= df['ST_NM'].str.title(),
autocolorscale=False,
colorscale='Reds',
marker_line_color='darkgreen',
colorbar=dict(
title={'text': "Amount"},
thickness=35,
len=1.0,
bgcolor='rgba(255,255,255,0.6)',
xanchor='right',
x=0.0,
yanchor='bottom',
y=0.0
),
))
fig.update_geos(
visible=True,
projection=dict(
type='conic conformal',
parallels=[12.472944444, 35.172805555556],
rotation={'lat': 24, 'lon': 80}
),
lonaxis={'range': [68, 98]},
lataxis={'range': [6, 38]}
)
fig.update_layout(
title=dict(
text="Average Overdue Amount over Total cases ",
xanchor='center',
x=0.5,
yref='paper',
yanchor='bottom',
y=0.9,
pad={'b': 0}
),
margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
height=850,
width=750
)
fig.show()
我也尝试过使用 geopandas,在该图上,我能够根据值绘制带有颜色的地图,但没有找到显示州名称和值的方法。
geopandas 的代码是:
fig, ax = plt.subplots(1, figsize=(10, 10))
ax.axis('off')
ax.set_title('ODVal/Cases distribution',
fontdict={'fontsize': '15', 'fontweight' : '3'})
merged.plot(column='ratio_od_cases',cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0', legend=True)
plt.text(,merged['State_Name'])
我认为在地图上添加文本最简单的方法是在 go.Scattergeo() 中使用文本模式并指定纬度和经度。从使用的geojson数据来看,geopandas用于计算文本显示的状态中心。
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from urllib import request
import json
url = "https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson"
with request.urlopen(url) as f:
geo_india = json.load(f)
import geopandas as gpd
df = gpd.read_file(url)
df["lon"] = df["geometry"].centroid.x
df["lat"] = df["geometry"].centroid.y
df['value'] = np.random.randint(5,50,36)
fig = go.Figure(data=go.Choropleth(
geojson=geo_india,
featureidkey='properties.ST_NM',
#locationmode='geojson-id',
locations=df['ST_NM'].str.title(), # To make lower case to CamelCase
z=df['value'],
text= df['ST_NM'].str.title(),
autocolorscale=False,
colorscale='Reds',
marker_line_color='darkgreen',
colorbar=dict(
title={'text': "Amount"},
thickness=35,
len=1.0,
bgcolor='rgba(255,255,255,0.6)',
xanchor='right',
x=0.0,
yanchor='bottom',
y=0.0
),
))
fig.update_geos(
visible=True,
projection=dict(
type='conic conformal',
parallels=[12.472944444, 35.172805555556],
rotation={'lat': 24, 'lon': 80}
),
lonaxis={'range': [68, 98]},
lataxis={'range': [6, 38]}
)
fig.add_trace(go.Scattergeo(
lon=df['lon'],
lat=df['lat'],
mode='text',
#text=df['ST_NM'].str.title(),
text=['{}<br>{}'.format(k,v) for k,v in zip(df['ST_NM'].str.title(), df['value'])],
textfont={'color': 'Green'},
name='',
))
fig.update_layout(
title=dict(
text="Average Overdue Amount over Total cases ",
xanchor='center',
x=0.5,
yref='paper',
yanchor='bottom',
y=0.9,
pad={'b': 0}
),
margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
height=850,
width=750
)
fig.show()