Home > Software engineering >  How to sort values in Rechart on x-axis in ascending order
How to sort values in Rechart on x-axis in ascending order

Time:03-19

I've 3 demo datasets to visualize in React using Recharts.js.

{ x: 80, y: 50, name: "Page A" },
{ x: 14, y: 80, name: "Page B" },
{ x: 70, y: 38, name: "Page C" },

enter image description here

Unfortunately, the values on the x-axis are not ordered correctly (80 -> 14 -> 70), but follow the order of objects in the data array.

const rechart = () => {
  return (
    <div>
      <ScatterChart width={400} height={400} data={data}>
        <XAxis dataKey="x" domain={[0, 100]} />
        <YAxis dataKey="y" domain={[0, 100]} axisLine={false} tick={false} />
        <Scatter data={data}>
          <LabelList dataKey="name" position="right" />
        </Scatter>
      </ScatterChart>
    </div>
  );
};

What can I do to sort the values from 0 to 100, not Page A to Page C?

CodePudding user response:

Try sorting your data before passing it as props to the Scatter component

data.sort((a,b) => a.x - b.x)
const rechart = () => {
  const sortedData = data.sort((a,b) => a.x - b.x)
  return (
    <div>
      <ScatterChart width={400} height={400} data={data}>
        <XAxis dataKey="x" domain={[0, 100]} />
        <YAxis dataKey="y" domain={[0, 100]} axisLine={false} tick={false} />
        <Scatter data={sortedData}>
          <LabelList dataKey="name" position="right" />
        </Scatter>
      </ScatterChart>
    </div>
  );
};
  • Related