Creating ranged bar chart using recharts

684 views Asked by At

How can we define the bar range in the Bar Chart created using recharts. Is there a way using which we can do that?

For example I've two value startPos, endPos. Such that I want to create a Bar which should start from the point(startPos) and should end at(endPos)

1

There are 1 answers

0
Taha LAGHZALI On

It's a little bit difficult but still possible, recharts give you the ability to create custom shapes(property shape) but you have to implement it yourself.

Here is a code that i have made for this example the data Key is volume (and it can take an array with two values [startPos,endPos])

const moveTo = (x, y, { ry = 0, rx = 0 }) => `M${x + rx}, ${y + ry}`;
const lineTo = (x, y, { ry = 0, rx = 0 }) => `L${x + rx}, ${y + ry}`;
const quadraticCurveTo = (x, y, { ry = 0, rx = 0 }) => `Q${x}, ${y} ${x + rx} ${y + ry}`;

const drawRoundEdgesRectangle = (points, radius,
  { radiusTop = true, radiusBottom = false }) => `${moveTo(points[0].x, points[0].y, { rx: radiusTop ? radius : 0 })}
  ${quadraticCurveTo(points[0].x, points[0].y, { ry: radiusTop ? radius : 0 })}
  ${lineTo(points[1].x, points[1].y, { ry: radiusBottom ? -radius : 0 })}
  ${quadraticCurveTo(points[1].x, points[1].y, { rx: radiusBottom ? radius : 0 })}
  ${lineTo(points[2].x, points[2].y, { rx: radiusBottom ? -radius : 0 })}
  ${quadraticCurveTo(points[2].x, points[2].y, { ry: radiusBottom ? -radius : 0 })}
  ${lineTo(points[3].x, points[3].y, { ry: radiusTop ? radius : 0 })}
  ${quadraticCurveTo(points[3].x, points[3].y, { rx: radiusTop ? -radius : 0 })}
  Z`;
const RoundBar = (props) => {
      const {
        fill, x, y, width, height, rem, volume,
      } = props;
      const color = rem ? 'url(#linearGradient-rem)' : fill;
      const radius = 3;
      const haveRadiusBottom = isArray(volume) && volume[1] - volume[0] !== 0 && volume[0] !== 0;
      const haveRadiusTop = (isArray(volume) && volume[1] - volume[0] !== 0)
        || (!isArray(volume) && volume !== 0);
      const points = [
        { x, y }, { x, y: y + height }, { x: x + width, y: y + height }, { x: x + width, y },
      ];
      const d = drawRoundEdgesRectangle(points, radius,
        { radiusBottom: haveRadiusBottom, radiusTop: haveRadiusTop });
      return <path d={d} stroke="none" fill={color} />;
    };

here is my component bar which is inside Barchart :

<Bar
                  barSize={54}
                  animationBegin={400}
                  animationDuration={400} 
                  dataKey={!sales ? 'sales' : 'volume'}
                  fill={sales ? 'url(#linearGradient-1)' : 'url(#linearGradient-2)'}
                  shape={<RoundBar />}
                >