如何为每个条形图设置不同的颜色 ApexChart

Sud*_*hne 10 charts reactjs apexcharts

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

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

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"
    />
);
Run Code Online (Sandbox Code Playgroud)

当前图表

Ahm*_*ınç 27

您需要在键distributed: true内添加选项以及将选项添加为数组。您可以查看此 stackblitz的实时工作示例。你的最终代码将是这样的:barplotOptionscolors

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"
    />
);
Run Code Online (Sandbox Code Playgroud)