DEV Community

Aman Pareek
Aman Pareek

Posted on • Edited on

2 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay