2

I am building a React JS application. In my application, I need to display data in Bar chart. I am using this library, https://www.npmjs.com/package/react-chartjs-2. Now, I have a chart like this.

enter image description here

This is the code for that

const colorCode = '#1478BD';
const state = {
  data: {
    labels: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
    datasets: [
      {
        fill: true,
        label: null,
        backgroundColor: colorCode,
        borderColor: colorCode,
        borderWidth: 2,
        data: [65, 59, 80, 81, 56, 65, 59, 80, 81, 56, 40, 56]
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        display: false
      },
    },
    scales: {
      x: {
        grid: {
          display: false
        },
        beginAtZero: false,
        ticks: {
          color: colorCode,
        }
      },
      y: {
        grid: {
          display: false,
        },
        beginAtZero: true,
        ticks: {
          color: colorCode,
        }
      }
    },
  }
}


<Bar
            type={"bar"}
            height={170}
            data={state.data}
            options={state.options}
          />

What I want to do is that I also want to add some background so that I can customing the styling for the remaining gap for each bar. Something like this.

enter image description here

Ass you can see, we can see the background when the bar is not filling the entire height. How can I do that? Is there an option for that?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

0

You can use the beforeDraw plugin for this

const plugins = [
  {
    beforeDraw: function (chart) {
      if (chart.chartArea) {
        var ctx = chart.ctx;
        var chartArea = chart.chartArea;
        var barArray = chart.getDatasetMeta(0).data;

        ctx.fillStyle = "#EEE";

        for (let i = 0; i < barArray.length; i++) {
          const { x, width } = barArray[i];

          ctx.fillRect(
            x - width / 2,
            chartArea.top,
            width,
            chartArea.bottom - chartArea.top
          );
        }
      }
    }
  }
];


<Bar
  type={"bar"}
  height={170}
  data={state.data}
  options={state.options}
  plugins={plugins}
/>
Andrey
  • 928
  • 1
  • 12
  • 20