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

Plotly重叠条形图开发问题:代码未生成预期单条重叠效果

问题排查与代码修正

你的代码当前是将每个分类作为独立的x轴条目生成多个并列条形,而非单个条形上的分段重叠效果。要实现每个图表仅展示一个条形、各分段相互重叠的需求,需对数据结构和Plotly配置做如下调整:

关键修改点

  • 将x轴设置为单一固定值,让所有分段都定位在同一个条形位置
  • 把每个分类的数据拆分为独立的trace(而非单个trace包含所有分类)
  • 每个图表传入所有分段的trace数组,而非单个trace
  • 统一设置条形宽度,确保分段完全重叠

修正后的完整代码

// Function to generate environmental overlapping bar chart
function generateEnvironmentalGraph(electricVehicle, gasVehicle) {
    const categories = [
        "Production du carburant (tCO2e)",
        "Fabrication du vehicule (tCO2e)",
        "Fabrication de batterie (tCO2e)",
        "Emissions d'echappement (tCO2e)"
    ];

    // 生成电动车的每个分段trace
    const electricTraces = categories.map(category => {
        const value = electricVehicle ? electricEnvironmentData[electricVehicle][category] : 0;
        return {
            x: ["环境影响总计"], // 统一x轴为单一值
            y: [value],
            type: 'bar',
            name: category,
            marker: {
                color: category === "Production du carburant (tCO2e)" ? 'rgba(55,128,191,0.7)' :
                       category === "Fabrication du vehicule (tCO2e)" ? 'rgba(100,200,100,0.7)' :
                       category === "Fabrication de batterie (tCO2e)" ? 'rgba(255,165,0,0.7)' : 'rgba(219,64,82,0.7)',
                line: { width: 1 }
            },
            width: 0.8 // 设置条形宽度,确保完全重叠
        };
    });

    // 生成汽油车的每个分段trace
    const gasTraces = categories.map(category => {
        const value = gasVehicle ? gasEnvironmentData[gasVehicle][category] : 0;
        return {
            x: ["环境影响总计"],
            y: [value],
            type: 'bar',
            name: category,
            marker: {
                color: category === "Production du carburant (tCO2e)" ? 'rgba(55,128,191,0.7)' :
                       category === "Fabrication du vehicule (tCO2e)" ? 'rgba(100,200,100,0.7)' :
                       category === "Fabrication de batterie (tCO2e)" ? 'rgba(255,165,0,0.7)' : 'rgba(219,64,82,0.7)',
                line: { width: 1 }
            },
            width: 0.8
        };
    });

    const layout = {
        title: 'Environmental Impact Comparison',
        xaxis: { title: '' },
        yaxis: { title: 'tCO2e' },
        barmode: 'overlay', // 保持重叠模式
        showlegend: true // 显示图例区分各分段
    };

    // 传入所有分段trace到对应图表
    Plotly.newPlot('electricEnvironmentGraph', electricTraces, layout);
    Plotly.newPlot('gasEnvironmentGraph', gasTraces, layout);
}

额外说明

  • 代码中已为每个分类分配了专属半透明色,你可根据需求自行调整颜色值
  • 若需要让分段按数值从大到小叠加(最大值在底层),可先对categories对应的数据进行排序后再生成trace数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:37:46