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

如何在Plotly Express美国人口Choropleth图中修改特定州边框颜色

实现特定州的边框高亮

可以通过修改Plotly图表的trace属性来实现特定州的边框颜色自定义,具体步骤如下:

  1. 修正代码拼写错误:你当前代码里的px.chorolpeth是拼写错误,正确应为px.choropleth。
  2. 定位人口极值州:从数据中找出人口最多和最少的州。
  3. 自定义边框颜色数组:为每个州设置默认边框色,再将目标州的边框色替换为高亮色。
  4. 更新图表属性:把自定义的边框颜色数组应用到图表中,同时可调整边框宽度增强高亮效果。

完整代码示例:

import pandas as pd
import plotly.express as px

df = pd.read_csv("state_pop.csv")

# 找出人口最多和最少的州
max_state = df.loc[df['population'].idxmax(), 'state']
min_state = df.loc[df['population'].idxmin(), 'state']

# 生成基础地图
fig = px.choropleth(df,
                    locations="state",
                    scope="usa",
                    color="population",
                    locationmode="USA-states",
                    color_continuous_scale="blues",
                    )

# 获取图表的trace对象
trace = fig.data[0]

# 创建边框颜色数组,默认使用灰色
line_colors = ['gray'] * len(trace.locations)

# 找到极值州在locations中的索引,替换为高亮红色
if max_state in trace.locations:
    max_idx = list(trace.locations).index(max_state)
    line_colors[max_idx] = 'red'
if min_state in trace.locations:
    min_idx = list(trace.locations).index(min_state)
    line_colors[min_idx] = 'red'

# 更新图表的边框样式
fig.update_traces(
    marker=dict(
        line=dict(
            color=line_colors,
            width=2  # 调整边框宽度,让高亮更明显
        )
    )
)

fig.show()

说明

  • 你可以根据需求替换'red'为其他高亮颜色,比如'#ff0000'(自定义十六进制色)。
  • 调整width参数可以改变边框粗细,数值越大边框越粗。
  • 如果需要区分最多和最少的州,可以给它们设置不同的边框颜色(比如最多用红色,最少用橙色)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:52:04