ApexChart 如何为每个柱设置不同的颜色

how to set different color every bar ApexChart

我正在为一个项目使用 ApexChart,我想为每个条设置不同的颜色。我将数据数组和颜色数组传递给组件,根据颜色数组索引,相关数据栏应该是彩色的。

当前实现如下,我厌倦了 colors: 方法,但它只获取颜色数组的第一种颜色。

const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            horizontal: true,
            barHeight: '85%',
        },
    },
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },  
    },     
};

const series = [
    {
        data: exampleChartData.data || [],

    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);

您需要在 plotOptionsbar 键内添加 distributed: true 选项,并将 colors 选项添加为数组。您可以查看 this sandbox 的实际工作示例。你的最终代码将是这样的:

const options: ApexOptions = {
    chart: {
        height: 200,
        type: 'bar',
        offsetY: 16,
        toolbar: {
            show: false,
        },
    },
    plotOptions: {
        bar: {
            distributed: true, // this line is mandatory
            horizontal: true,
            barHeight: '85%',
        },
    },
    colors: [ // this array contains different color code for each data
        "#33b2df",
        "#546E7A",
        "#d4526e",
        "#13d8aa",
        "#A5978B",
        "#2b908f",
        "#f9a3a4",
        "#90ee7e",
        "#f48024",
        "#69d2e7"
    ],
    dataLabels: {
        enabled: false,
    },
    xaxis: {
        position: 'top',
    },
    yaxis: {
        show: false,
    },
    grid: {
        padding: {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        },  
    },     
};

const series = [
    {
        data: exampleChartData.data || [],
    }
];

return (
    <Chart
        options={options}
        series={series}
        type="bar"
        height={740}
        className="apex-charts"
        dir="ltr"
    />
);