Search code examples
javascriptreactjsrecharts

Recharts join disconnected lines


When there is null in the time-series data, Recharts is not joining the dots and considering it as an independent point in the Line chart.

I want to join the disconnected points. How can I achieve that?

const data = [
  {
    ts: 1641275508,
    uv: 4000,
    pv: null,
    amt: 2400
  },
  {
    ts: 1641275608,
    uv: null,
    pv: 1398,
    amt: 2210
  },
  {
    ts: 1641275708,
    uv: 2000,
    pv: 9800,
    amt: 2290
  },
  {
    ts: 1641275808,
    uv: null,
    pv: 3908,
    amt: 2000
  },
  {
    ts: 1641275908,
    uv: 1890,
    pv: null,
    amt: 2181
  },
  {
    ts: 1641276008,
    uv: 2390,
    pv: 3800,
    amt: 2500
  },
  {
    ts: 1641276108,
    uv: null,
    pv: 4300,
    amt: 2100
  }
];

Current Result Current Result

Expected Result Expected Result

https://codesandbox.io/s/simple-line-chart-forked-mozqo?file=/src/App.tsx


Solution

  • It can be achieved using connectNulls props by components like Line, Area etc.

        <LineChart
          width={500}
          height={300}
          data={data}
          margin={{
            top: 5,
            right: 30,
            left: 20,
            bottom: 5
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="ts" type={"number"} domain={["dataMin", "dataMax"]} />
          <YAxis />
          <Tooltip />
          <Legend />
          <Line type="monotone" connectNulls dataKey="pv" stroke="#8884d8" />
          <Line type="monotone" connectNulls dataKey="uv" stroke="#82ca9d" />
        </LineChart>
    

    Solution:

    https://codesandbox.io/s/simple-line-chart-forked-mdkeb?file=/src/App.tsx

    Chart Render