DEV Community

Aman Pareek
Aman Pareek

Posted on • Updated on

ChartJS color Below Zero

I was stuck back 3 months ago and know the solution now

You can use colorchartjs

import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import { colorchartjs } from "colorchartjs";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

function Chart(props) {
  var colordata2 = colorchartjs(props.data2, "green", "red", 0);
// Here we have to give array data and greater than and more than color and starting point 

  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: "top",
      },
      title: {
        //position: 'bottom',
        display: true,
        text: props.charttitle,
      },
    },
  };

  const labels = props.data1;

  const data = {
    labels,
    datasets: [
      {
        label: "PNL",
        data: props.data2,
        borderColor: "green",
        backgroundColor: colordata2, //Here pass the received data means colors
        hoverBackgroundColor: "grey",
        lineTension: 0,
      },
      {
        label: "FEE",
        data: props.data3,
        backgroundColor: "orange",
        lineTension: 0,
      },
    ],
  };

  return (
    <>
      <div style={{ width: "900px", margin: "auto" }}>
        <Bar options={options} data={data} />
      </div>
    </>
  );
}

export default Chart;

Enter fullscreen mode Exit fullscreen mode

Use this in component

<div className="mgchart">
                      <Bar
                        charttitle={`Chart for ${data._id} side`}
                        data1={data.chartstocks}
                        data2={data.chartpnl}
                        data3={data.chartfee}
                      />
                    </div>


Enter fullscreen mode Exit fullscreen mode

Top comments (0)