SpaceCowboy2071
SpaceCowboy2071

Reputation: 1155

Positive Negative Bar Chart Color w/ Recharts

I'm trying to create a positive / negative bar chart using Rechart, but I don't know how to have the color fill set conditionally if the value is positive or negative. I'd like to have something like this: enter image description here

Example code from docs:

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

const data = [
  {
    name: 'Page A', uv: 4000, pv: 2400, amt: 2400,
  },
  {
    name: 'Page B', uv: -3000, pv: 1398, amt: 2210,
  },
  {
    name: 'Page C', uv: -2000, pv: -9800, amt: 2290,
  },
  {
    name: 'Page D', uv: 2780, pv: 3908, amt: 2000,
  },
  {
    name: 'Page E', uv: -1890, pv: 4800, amt: 2181,
  },
  {
    name: 'Page F', uv: 2390, pv: -3800, amt: 2500,
  },
  {
    name: 'Page G', uv: 3490, pv: 4300, amt: 2100,
  },
];

export default class Example extends PureComponent {
  static jsfiddleUrl = 'https://jsfiddle.net/alidingling/q68cz43w/';

  render() {
    return (
      <BarChart
        width={500}
        height={300}
        data={data}
        margin={{
          top: 5, right: 30, left: 20, bottom: 5,
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <ReferenceLine y={0} stroke="#000" />
        <Bar dataKey="pv" fill="#8884d8" />
        <Bar dataKey="uv" fill="#82ca9d" />
      </BarChart>
    );
  }
}

Does anybody have example code that could accomplish this please?

Upvotes: 0

Views: 4639

Answers (2)

Oybek Toshmatov
Oybek Toshmatov

Reputation: 427

You can do something like this. It worked for me! By the way, I only used uv here, You can also use pv similar to how I did.

`<Bar
        dataKey='uv'
    >
        {data.map((datum, entry, index) => (
            <Cell
                key={`cell-${index}`}
                fill={
                    datum.uv > 0
                        ? 'green'
                        : 'red'
                }
            />
        ))}
    </Bar>`

Upvotes: 0

SpaceCowboy2071
SpaceCowboy2071

Reputation: 1155

Ah, I need to use the <Cell> component!
https://recharts.org/en-US/api/Cell

<BarChart width={730} height={250} data={data}>
  <Bar dataKey="value">
    {
      data.map((entry, index) => (
        <Cell key={`cell-${index}`} stroke={colors[index]}  strokeWidth={index === 2 ? 4 : 1}/>
      ))
    }
  </Bar>
</BarChart>

Upvotes: 2

Related Questions