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

Plotly实现基于不同列值调整柱状图透明度

基于数据列调整柱状图透明度并保留离散色阶的实现

以下是满足需求的完整代码实现,同时附带关键步骤说明:

import plotly.express as px
import numpy as np

# 获取加拿大的gapminder数据
data_canada = px.data.gapminder().query("country == 'Canada'")

# 1. 为年份划分分组,用于设置离散色阶
data_canada['year_group'] = np.select(
    [
        (data_canada['year'] >= 1980) & (data_canada['year'] < 1990),
        (data_canada['year'] >= 1990) & (data_canada['year'] < 2000),
        (data_canada['year'] >= 2000)
    ],
    ['1980-1990', '1990-2000', '2000+']
)

# 2. 根据gdpPercap生成对应的透明度值
data_canada['opacity'] = np.where(data_canada['gdpPercap'] < 20000, 0.5, 1)

# 3. 绘制带离散色阶的柱状图
fig = px.bar(
    data_canada,
    x='year',
    y='pop',
    color='year_group',
    color_discrete_map={
        '1980-1990': 'green',
        '1990-2000': 'red',
        '2000+': 'blue'
    }
)

# 4. 为每个柱状条单独设置透明度
for i in range(len(fig.data)):
    fig.data[i].marker.opacity = data_canada['opacity'].tolist()

fig.show()

关键步骤说明

  • 年代分组:用np.select按年份区间给数据打分组标签,方便后续绑定自定义颜色;
  • 透明度生成:通过np.where快速生成符合条件的透明度值,无需手动遍历判断;
  • 离散色阶设置:通过color_discrete_map直接指定各年代组的颜色,实现需求中的配色要求;
  • 透明度绑定:遍历图中每个数据系列,将预先生成的透明度列表赋值给对应柱子,实现按需调整透明度的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:25:17