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

ApexCharts如何根据X轴值设置柱状图颜色?

根据X轴值设置柱状图颜色的解决方案

你需要实现的是根据X轴分类值(而非Y轴数据)设置柱子颜色:X轴值>=0时为绿色,<0时为红色。原来的代码用了colors.ranges,这个是基于Y轴值判断的,不符合需求,你可以改用ApexCharts的自定义颜色函数来实现。

修改后的完整代码

var options = {
    series: [{
        name: 'Occorrenze',
        data: [2, 10, 45, 70, 47, 36, 7, 3] // _jSon.occorenze
    }],              
    chart: {
        height: 415,
        type: 'bar',
        foreColor: '#ffffff'
    },
    plotOptions: {
        bar: {
            dataLabels: {
                position: 'top'
            },
            colors: {
                // 自定义颜色函数,根据X轴值判断颜色
                custom: function({ seriesIndex, dataPointIndex }) {
                    // 获取当前柱子对应的X轴分类值
                    const xAxisValue = options.xaxis.categories[dataPointIndex];
                    // 判断X轴值,返回对应颜色
                    return xAxisValue >= 0 ? '#00A86B' : '#FF4D4F';
                }
            }                        
        }
    },                
    dataLabels: {
        enabled: true,
        formatter: function (val) {
            return val;
        },
        offsetY: -20,
        style: {
            fontSize: '12px',
            colors: ["#fff"]
        }
    },
    xaxis: {
        type: 'category',
        categories: [3, 2, 1, 0, -0, -1, -2, 3], // _jSon.percentuali,
        labels: {
            show: true,
            formatter: function (val) {
                return val + "%";
            }
        },
        tooltip: {
            enabled: true,
        }                    
    },
    yaxis: {
        show: true,
        labels: {
            show: false,
            formatter: function (val) {
                return val;
            }
        },
        tooltip: {
            y: {
                formatter: function (val) {
                    return "Occorrenze"
                }
            }
        }
    }               
};

var chart = new ApexCharts(document.querySelector("#historical_occurrences"), options);
chart.render();

关键说明

  • 替换了原来的colors.ranges为colors.custom函数,这个函数会为每个数据点单独计算颜色。
  • 通过dataPointIndex可以拿到当前柱子在X轴分类数组中的位置,进而获取对应的X轴值。
  • 根据X轴值的判断结果,返回绿色(#00A86B)或红色(#FF4D4F),你可以根据需求替换成自己想要的颜色代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:44:58