Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the color of each bar in Recharts?

I have a bar graph on one of my React pages. It gets data from props that are passed on from another page. I have a bar graph showing three different pieces of data. One shows, "Correct", the other shows, "Incorrect", and the last shows, "Total". I would like to have the color of each bar be different. I've tried using the Cell feature but couldn't get it to work. I also tried changing the name of each piece of data but no luck. Unfortunately, there's not a lot of documentation out there for Recharts. Anybody have any ideas?

import React from 'react';
import {
    ResponsiveContainer, BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts';

export default class GameChart extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            axes: [
                { primary: true, type: 'ordinal', position: 'left' },
                { position: 'bottom', type: 'linear', stacked: true }
            ],
            series: {
                type: 'bar'
            },
            chartData: [
                {
                    name: 'Correct',
                    total: 0,
                },
                {
                    name: 'Incorrect',
                    total: 0,
                },
                {
                    name: 'Total',
                    total: 0,
                },
            ],
            chartLayout: {
                title: 'Math Game Results',
                yaxis: {
                    showticklabels: false
                },
            }
        }
    }

    componentDidUpdate(prevProps) {
        if (prevProps.chartData.totalCounter !== this.state.chartData[2].total) {
            let tempState = this.state;
            tempState.chartData = [
                {
                    name: 'Correct',
                    total: this.props.chartData.correctCounter,
                },
                {
                    name: 'Incorrect',
                    total: this.props.chartData.incorrectCounter,
                },
                {
                    name: 'Total',
                    total: this.props.chartData.totalCounter,
                },
            ];
            this.setState(tempState);
        }
    }

    render () {
        return (
            <div>
                {
                    (this.state.chartData[2].total > 0) ?
                        (<ResponsiveContainer width="95%" height={225}>
                            <BarChart
                                data={this.state.chartData.slice()}
                                layout="vertical" barCategoryGap={5}
                                margin={{top: 5, right: 30, left: 20, bottom: 5,}}
                            >
                                <XAxis
                                    type="number"
                                    stroke="#000000"
                                />
                                <YAxis
                                    type="category"
                                    stroke="#000000"
                                    dataKey="name"
                                />
                                <Tooltip
                                    wrapperStyle={{ width: 100, backgroundColor: '#ccc' }}
                                    formatter={function(name) {return `${name}`}}
                                />
                                <Bar
                                    dataKey="total"
                                    fill="#00a0fc"
                                    stroke="#000000"
                                    strokeWidth={1}
                                />
                            </BarChart>
                        </ResponsiveContainer>
                        ):
                        (null)
                }
            </div>
        );
    }
}

Here's a picture of the current setup. As you can see, each bar has the same color. enter image description here

like image 649
Hiebs915 Avatar asked Jan 08 '21 21:01

Hiebs915


People also ask

How do you color each bar in tableau?

If you have (for example) a bar chart of sales against region, drag and drop the region into the Color on the Marks shelf. Once the Colour legend appears, click the little drop down at the top right of the legend box and select Edit Colors to assign the palette you wish, or set individual colours.

How do you change the color of a bar plot?

Click the Bar Chart in the Object Manager to select it. In the Property Manager, click on the Fill tab. Check the box next to Use color table. The bar chart will change to a variety of default colors.

How do you change the color of the bar in SAS?

If you have SAS 9.3 or later, you can do this using the SGPLOT procedure. Use LIMITATTRS to change the color of the error bars. You can change the color of the bars themselves using FILLATTRS.

How to colorize the cursor in recharts?

This methodology can be applied whether you want to colorise the bar and potentially the cursor={{ fill }}color. The only missing bit (to know which bar was entered) is supplied as second argument in Recharts' mouseEvent functions as: onMouseEnter((barPayload, index) => {})

How do I change the color of my chart?

In the upper-right corner, next to the chart, click Chart Styles. Click Color and pick the color scheme you want, or click Style and pick the option you want. Want more?

How do I change the color of individual bars in PowerPoint?

How do you change the color of individual bars in PowerPoint? On a chart, select the individual data marker that you want to change. On the Format tab, in the Shape Styles group, click Shape Fill. Do one of the following: To use a different fill color, under Theme Colors or Standard Colors, click the color that you want to use.

How do I change the color of a negative bar chart?

You can also choose to automatically color columns below X-axis (negative values) differently from the ones above, by selecting ‘Invert if negative’ under Series Options > Fill > Select color for negative values. I worked at Tableau Software from 2006 to 2017. Author has 69 answers and 202.4K answer views Apr 4 What is a stacked bar chart?


2 Answers

Ok, thanks to @c0m1t I got it working. All I had to do was make a list of colors above the state class!

import React from 'react';
import {
    BarChart, Bar, XAxis, Cell, YAxis, Tooltip, ResponsiveContainer,
} from 'recharts';

const barColors = ["#1f77b4", "#ff7f0e", "#2ca02c"]

export default class Example extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: [
                {
                    name: "Correct",
                    total: this.props.chartData.correctCounter
                },
                {
                    name: "Incorrect",
                    total: this.props.chartData.incorrectCounter
                },
                {
                    name: "Total",
                    total: this.props.chartData.totalCounter
                }
            ]
        }
    }

    render() {
        return (
            <ResponsiveContainer width="95%" height={450}>
                <BarChart
                    data={this.state.chartData.slice()}
                    margin={{ top: 20, right: 20, left: 20, bottom: 5, }}
                    data={this.state.chartData}
                >
                <XAxis
                    dataKey="name"
                    stroke="#000000"
                />
                <YAxis
                    stroke="#000000"
                />
                <Tooltip
                    wrapperStyle={{ width: 100, backgroundColor: '#ccc' }}
                    formatter={function(total) {return `${total}`}}
                />
                <Bar
                    dataKey="total"
                    fill="#00a0fc"
                    stroke="#000000"
                    strokeWidth={1}
                >
                    {
                        this.state.chartData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={barColors[index % 20]} />
                        ))
                    }
                </Bar>
                </BarChart>
            </ResponsiveContainer>
        );
    }
}

Now each bar has a different color. New bar chart with different color for each bar.

like image 133
Hiebs915 Avatar answered Oct 22 '22 06:10

Hiebs915


You can add the fill color to the chartData directly using the fill key:

[
    {
        name: 'Correct',
        total: 0,
        fill: '#1f77b4',
    },
    {
        name: 'Incorrect',
        total: 0,
        fill: '#ff7f0e',
    },
    {
        name: 'Total',
        total: 0,
        fill: '#2ca02c',
    },
]
like image 1
Ben Sturmfels Avatar answered Oct 22 '22 06:10

Ben Sturmfels