Sudaraka Senevirathne
Sudaraka Senevirathne

Reputation: 377

how to set different color every bar ApexChart

I'm using ApexChart for a project, and I want to set different colors for each bar. I pass the data array and the color array to the component, based on the color array index the relevant data bar should be colored.

Current implementation as below, I tired colors: method but it only gets the first color of the color array.

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"
    />
);

current chart

Upvotes: 12

Views: 15025

Answers (1)

Ahmet Emre Kilinc
Ahmet Emre Kilinc

Reputation: 6895

You need to add distributed: true option inside bar key of plotOptions as well as adding the colors option as array. You can take a look at this stackblitz for a live working example. And your final code will be like this:

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"
    />
);

Upvotes: 38

Related Questions