React ReCharts Creating 2 different lines from same Json object element(which has 2 different values)

Viewed 19

Im pretty new to React/ReCharts I have a JSON data set like below.

[
    {
        "time": "00:00"
        "SumofDays": 100,
        "schedule": "sch_1"
    },
    {
        "time": "00:00"
        "SumofDays": 100,
        "schedule": "sch_2"
    },
    {
        "time": "01:00"
        "SumofDays": 200,
        "schedule": "sch_1"
    },
     {
      
        "time": "01:00"
        "SumofDays": 200,
        "schedule": "sch_2"
    }....

]

I need to render Above data in a Line graph. With 2 different colored lines for the two different schedules .

<LineChart width={1300} height={300} data={graphData}
            margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="time" />
            <YAxis  dataKey="SumofDays" />
            <Tooltip />
            <Legend />
            <Line type="monotone" dataKey="schedule" stroke="#0095FF" />
         </LineChart>

Im unable to rendering the Line because the Line dataKey is not unique. I tried couple of options But still no luck. Any help will be much appreciated.

Thanks.

1 Answers

You need to manipulate your current graphData to get both values of two schedules in the same object like this:

const sch1Data = graphData.filter((d) => {
    return d.schedule === "sch_1";
  });
  const sch2Data = graphData.filter((d) => {
    return d.schedule === "sch_2";
  });

  const finalGrapData = sch1Data.map((d, index) => {
    const sch2CurrentData = sch2Data.find((d2) => d.time === d2.time);

    const finalData = {
      ...d,
      sch_1: d.SumofDays,
      sch_2: sch2CurrentData?.SumofDays
    };
    return finalData;
  });

  return (
    <LineChart
      width={500}
      height={300}
      data={finalGrapData}
      margin={{
        top: 5,
        right: 30,
        left: 20,
        bottom: 5
      }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="time" />
      <YAxis />
      <Tooltip />
      <Legend />
      <Line
        type="monotone"
        dataKey="sch_1"
        stroke="#8884d8"
        activeDot={{ r: 8 }}
      />
      <Line type="monotone" dataKey="sch_2" stroke="#82ca9d" />
    </LineChart>
  );

You can take a look at this sandbox for a live working example of this solution.

Related