ParthS007
ParthS007

Reputation: 2689

How to change the width of the bar in bar chart in react-charts?

I am implementing the bar chart and I am stuck with the following thing:

Sometimes, the width of the bar is too much, it looks like the graph is broken as it overlaps with the axes. What approach should I follow to keep the bar width in control according to data?

Here is the data sample and how the graph looks like. I have added the code sandbox also.

const dataOne = [
    {
      label: Translate.string('Events'),
      data: [[2018, 3], [2019, 2], [2020, 1]],
    },
  ];

Screenshot from 2020-03-09 16-11-37

Edit epic-bohr-05txo

Let me know if I have to provide any other information. I have posted this issue here also.

Upvotes: 0

Views: 6115

Answers (2)

ParthS007
ParthS007

Reputation: 2689

After diving deep in the library, I found that there is a bug in calculating CSS transforms for rect elements for bar.

I was not able to found a full-proof way of solving this but I came up with a workaround (adding null values in the start and end of the data) which is working well for my use case and may help someone else to solve their problem so thought of adding the workaround as an answer.

import moment from "moment";
import React from "react";
import { Chart } from "react-charts";

import "./styles.css";

export default function App() {
  const dataone = React.useMemo(
    () => [
      {
        label: "Event",
        data: [
          [moment(2010, "YYYY"), null],
          [moment(2011, "YYYY"), 3],
          [moment(2012, "YYYY"), 2],
          [moment(2013, "YYYY"), 1],
          [moment(2015, "YYYY"), 3],
          [moment(2016, "YYYY"), null]
        ]
      }
    ],
    []
  );
  const options = {
    scales: {
      xAxes: [
        {
          barPercentage: 0.4
        }
      ]
    }
  };
  const series = { type: "bar" };
  const axes = React.useMemo(
    () => [
      { primary: true, type: "time", position: "bottom" },
      { type: "linear", position: "left" }
    ],
    []
  );

  return (
    <>
      <div
        style={{
          width: "600px",
          height: "300px"
        }}
      >
        <Chart
          data={dataone}
          options={options}
          axes={axes}
          series={series}
          tooltip
        />
      </div>
    </>
  );
}

Edit react charts bar chart

Upvotes: 1

Omolewa Stephen
Omolewa Stephen

Reputation: 421

The attribute is actually stored in scales.xAxes ("Options for xAxes" table).

So you just have to edit your chart this way :

var options = {
    scales: {
        xAxes: [{
            barPercentage: 0.4
        }]
    }
}

And this will be good for some references but particularly see this too

Upvotes: 1

Related Questions