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

使用Plotly Express的facet_col时如何设置独立色条?

实现带独立色条的同步动画子图(Plotly)

你可以通过Plotly Graph Objects手动构建子图和动画帧的方式,实现每个子图独立色条、自定义配色及z范围的同步动画效果。Plotly Express的facet_col机制默认共享色条,无法直接满足需求,改用手动构建的方式更灵活。

完整实现代码

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import xarray as xr

# 加载并预处理数据集
ds = xr.tutorial.open_dataset('eraint_uvz').sel(level=500)
data = ds.to_array().transpose('month', ...)
variables = data['variable'].values
months = data['month'].values

# 定义每个变量的独立配置:z最小值、z最大值、配色方案
var_config = {
    'u': {'zmin': -25, 'zmax': 25, 'colorscale': 'RdBu'},
    'v': {'zmin': -25, 'zmax': 25, 'colorscale': 'RdBu_r'},
    'z': {'zmin': 4600, 'zmax': 5800, 'colorscale': 'Viridis'}
}

# 创建子图,为每个子图分配独立的颜色轴
fig = make_subplots(
    rows=1, cols=3,
    subplot_titles=variables,
    specs=[[{'coloraxis': 'coloraxis1'}, {'coloraxis': 'coloraxis2'}, {'coloraxis': 'coloraxis3'}]]
)

# 构建所有动画帧
frames = []
for month in months:
    current_month_traces = []
    for col_idx, var in enumerate(variables, 1):
        # 获取当前月份当前变量的数据
        var_data = data.sel(month=month, variable=var).values
        config = var_config[var]
        # 创建对应子图的热力图trace
        trace = go.Heatmap(
            z=var_data,
            x=data['longitude'].values,
            y=data['latitude'].values,
            zmin=config['zmin'],
            zmax=config['zmax'],
            colorscale=config['colorscale'],
            coloraxis=f'coloraxis{col_idx}',
            showscale=True  # 显示当前子图的独立色条
        )
        current_month_traces.append(trace)
    # 将当前月份的所有子图trace打包为一个动画帧
    frames.append(go.Frame(data=current_month_traces, name=str(month)))

# 设置初始显示的帧(第一个月份数据)
initial_traces = []
for col_idx, var in enumerate(variables, 1):
    var_data = data.sel(month=months[0], variable=var).values
    config = var_config[var]
    initial_traces.append(go.Heatmap(
        z=var_data,
        x=data['longitude'].values,
        y=data['latitude'].values,
        zmin=config['zmin'],
        zmax=config['zmax'],
        colorscale=config['colorscale'],
        coloraxis=f'coloraxis{col_idx}',
        showscale=True
    ))
fig.add_traces(initial_traces)

# 配置每个颜色轴的参数
for col_idx, var in enumerate(variables, 1):
    config = var_config[var]
    fig.update_layout(
        **{
            f'coloraxis{col_idx}': {
                'zmin': config['zmin'],
                'zmax': config['zmax'],
                'colorscale': config['colorscale']
            }
        }
    )

# 配置动画控制控件
fig.update_layout(
    updatemenus=[{
        'type': 'buttons',
        'buttons': [{
            'label': '播放',
            'method': 'animate',
            'args': [None, {'frame': {'duration': 500, 'redraw': True}, 'fromcurrent': True}]
        }, {
            'label': '暂停',
            'method': 'animate',
            'args': [[None], {'frame': {'duration': 0, 'redraw': False}, 'mode': 'immediate'}]
        }]
    }],
    sliders=[{
        'steps': [{'method': 'animate', 'args': [[str(month)], {'frame': {'duration': 0, 'redraw': True}}], 'label': str(month)} for month in months],
        'currentvalue': {'prefix': '月份: '}
    }],
    height=500,
    width=1200
)

# 将动画帧添加到图中
fig.frames = frames

fig.show()

关键实现说明

  • 独立颜色轴:通过specs参数为每个子图分配专属的coloraxis,每个颜色轴可单独设置z范围和配色方案。
  • 同步动画帧:每个动画帧包含对应月份下所有子图的热力图数据,保证播放时所有子图同步切换。
  • 自定义配置:通过var_config字典统一管理每个变量的z范围和配色,便于后续调整维护。
  • 独立色条显示:每个热力图trace设置showscale=True,确保每个子图显示自己的色条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:55:14