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

如何修改Highcharts饼图扇区颜色?已实现百分比与图例

问题解决:Highcharts饼图颜色配置不生效的处理方案

问题背景

通过DataTables读取HTML表格的STATUS列(第3列),统计succeeded、failed、aborted三种状态的出现次数并生成Highcharts饼图。需求如下:

  • 成功(succeeded)对应绿色,失败(failed)对应红色,终止(aborted)对应紫红色
  • 饼图扇区显示百分比
  • 已实现百分比显示和图例功能,但颜色配置始终不生效

问题原因

你开启了Highcharts的styledMode: true,该模式下图表颜色由CSS样式控制,而非配置项中的colors属性,因此你在theme和plotOptions.pie里设置的颜色不会生效。

解决方案

提供两种可行处理方式,可根据需求选择:

方式1:关闭Styled Mode

直接移除styledMode: true配置,让Highcharts读取你设置的colors值:

chart: {
    type: 'pie'
    // 移除 styledMode: true
},
tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
    pie: {
        colors: ['green', 'red', 'fuchsia'],
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: { enabled: false },
        showInLegend: true
    }
},
// 其他配置保持不变

方式2:在数据中绑定对应颜色(保留Styled Mode)

若需保留styledMode,可在生成饼图数据时直接为每个状态指定对应颜色,确保状态与颜色一一映射:
修改chartData函数:

function chartData(table) {
    var counts = {};
    // 建立状态与颜色的映射表
    const statusColorMap = {
        'succeeded': 'green',
        'failed': 'red',
        'aborted': 'fuchsia'
    };

    table
        .column(3, { search: 'applied' })
        .data()
        .each(function (val) {
            counts[val] = counts[val] ? counts[val] + 1 : 1;
        });

    return Object.entries(counts).map((e) => ({
        name: e[0],
        y: e[1],
        color: statusColorMap[e[0]] // 为每个数据点绑定对应颜色
    }));
}

完整修改后的代码示例(方式2,保留Styled Mode)

// Create DataTable
const table = new DataTable('#example');

// Create chart
const chart = Highcharts.chart('demo-output', {
    chart: {
        type: 'pie',
        styledMode: true
    },
    tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: { enabled: false },
            showInLegend: true
        }
    },
    title: {
        text: 'Rundeck Jobs Stats'
    },
    series: [
        {
            data: chartData(table)
        }
    ]
});

// On each draw, update the data in the chart
table.on('draw', function () {
    chart.series[0].setData(chartData(table));
});

function chartData(table) {
    var counts = {};
    const statusColorMap = {
        'succeeded': 'green',
        'failed': 'red',
        'aborted': 'fuchsia'
    };

    table
        .column(3, { search: 'applied' })
        .data()
        .each(function (val) {
            counts[val] = counts[val] ? counts[val] + 1 : 1;
        });

    return Object.entries(counts).map((e) => ({
        name: e[0],
        y: e[1],
        color: statusColorMap[e[0]]
    }));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:10:22