我想绘制一个轮廓,突出显示使用 Plotly 从 GeoJSON 绘制的 Choropleth 地图中的形状(在我的例子中是通过 Dash)。
我有一个像这样的数据框“df”:
state (string) value (float)
STATE_1 50.0
STATE_2 30.5
STATE_3 66.2
我还有一个 GeoJSON 作为具有以下结构的对象加载:
{
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'id': 1,
'properties': {
'id': 'STATE_1',
},
'geometry': {'type': 'Polygon', 'coordinates': [...]},
},
...
]
}
我画了这样的底图:
fig = px.choropleth(
df,
geojson=my_geojson,
color='value',
locations='state',
featureidkey='properties.id',
projection='Mercator',
)
fig.update_geos(
fitbounds='locations',
visible=False,
)
fig.update_layout(
coloraxis=dict(
colorbar=dict(
title='',
orientation='h',
x=0.5,
y=0.1,
xanchor='center',
yanchor='top',
),
colorscale=[[0, '#04cc9a'], [1, '#5259ad']],
),
margin={"r": 0, "t": 0, "l": 0, "b": 0},
dragmode=False,
)
我尝试添加另一条轨迹来显示其中一个状态的轮廓,但未成功。我已经尝试过使用绘图表达和绘图对象,但没有结果。
我该怎么做?
最终对我有用的策略是:
它会是这样的:
# Create main figure as shown in the question
fig = ...
# Filter data and geojson to create the new trace
df_aux = df[df['state'] == 'STATE_1']
my_filtered_geojson = {...} # Filter so it has only one Feature, the one corresponding to STATE_1
# Replace value with dummy so we can fill the shape with a transparent color
df_aux ['value'] = 1
# Create aux figure
fig_aux = go.Figure(go.Choropleth(
geojson=my_filtered_geojson,
featureidkey='properties.id',
locationmode='geojson-id',
locations=df_aux['state'],
z=df_aux['value'], # The dummy value we have just set above
zmax=1,
zmin=0,
colorscale=[[0, 'rgba(0,0,0,0)'], [1, 'rgba(0,0,0,0)']], # Colors with alpha channel, both fully transparent
showscale=False,
marker=dict(
line=dict(
color='red',
width=4,
)
),
hoverinfo='skip', # Hide hover info so you still get the main figure's one
))
# Add new trace to the main figure
fig_principal.add_trace(fig_aux.data[0])
经过一些造型后,你应该能够得到这样的东西。在我的例子中,我显示了原始的等值线地图颜色,并在其上方以紫色突出显示了地图中的一个州。您还应该获得原始地图的悬停信息: