You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly生成的欧洲地图中让法国完全透明且不删除该国家

解决Plotly Choropleth中单独调整单个国家透明度的问题

你当前代码里的update_traces写法无法生效,原因是selector=dict(location="France")无法匹配到单个国家——Plotly的choropleth trace中,location属性是整个国家列表的数组,不是单个值,所以这个选择器找不到对应元素。

要实现“保留法国在国家列表中但完全不可见”的需求,有两种可行方法:

方法一:通过DataFrame绑定透明度列

直接给DataFrame添加透明度列,将法国的透明度设为0,其他国家按需设置,再绑定到trace的marker属性:

import pandas as pd
import plotly.express as px
import kaleido
from plotly.graph_objs import layout

df_france = pd.DataFrame({
    "country": ["France"]
})

df_ukraine = pd.DataFrame({
    "country": ["Ukraine"]
})

df = pd.concat([df_france, df_ukraine], ignore_index=True)
# 添加透明度列:法国设为0(完全不可见),乌克兰设为0.7
df["opacity"] = [0, 0.7]

fig = px.choropleth(df, locations="country",
                    locationmode="country names",
                    color="country",
                    scope="europe")

# 将透明度列绑定到marker的opacity属性
fig.update_traces(marker=dict(opacity=df["opacity"].tolist()))

fig.update_geos(
    resolution=50,
    fitbounds="locations",
    showcountries=False,
    countrycolor="#2d32aa"
    )

fig.update_layout(width=1935, height=1840, margin={"r":0,"t":0,"l":0,"b":0}, showlegend=False)

fig.show()

方法二:直接修改Trace的透明度数组

通过定位法国在trace的locations数组中的索引,单独设置其透明度为0:

import pandas as pd
import plotly.express as px
import kaleido
from plotly.graph_objs import layout

df_france = pd.DataFrame({
    "country": ["France"]
})

df_ukraine = pd.DataFrame({
    "country": ["Ukraine"]
})

df = pd.concat([df_france, df_ukraine], ignore_index=True)

fig = px.choropleth(df, locations="country",
                    locationmode="country names",
                    color="country",
                    scope="europe")

# 获取第一个trace(choropleth的主trace)
trace = fig.data[0]
# 找到法国在locations中的索引
france_index = trace.locations.index("France")
# 创建透明度数组,默认1,将法国的位置设为0
opacity_values = [1] * len(trace.locations)
opacity_values[france_index] = 0

# 更新trace的透明度
trace.marker.opacity = opacity_values

fig.update_geos(
    resolution=50,
    fitbounds="locations",
    showcountries=False,
    countrycolor="#2d32aa"
    )

fig.update_layout(width=1935, height=1840, margin={"r":0,"t":0,"l":0,"b":0}, showlegend=False)

fig.show()

两种方法都能实现需求:法国完全不可见,但仍保留在DataFrame的国家列表中,不会影响地图的fitbounds等基于国家列表的设置。

内容的提问来源于stack exchange,提问作者Federico Ferruti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:55:17