Search code examples
javascriptcssreactjsrecharts

Recharts scatter chart shows the lowest x value in tooltip when chart is resized


I am using Recharts Scatter chart to draw a bubble chart. As per requirements, the chart should be resizable to double the height or width. Before resizing everything is fine. But once the chart is resized, the tooltip shows an additional item (this is the lowest value in x axis data set across all data series). Once this happens, this incorrect tooltip persists even after changing chart back to original size.

Correct tooltip before resizing

Correct tooltip before resizing

Incorrect tooltip after resizing, here 45 is the lowest x value in both Type A and Type B

Incorrect tooltip after resizing, here 45 is the lowest x value in both Type A and Type B

Here is my code:

const BubbleChart = ({ data, width, height }) => {
  const drawCharts = (data) => {
    const charts = [];
    for (let i = 0; i < data.length; i++) {
      charts.push(
        <Scatter
          name={data[i].name}
          data={data[i].values}
          fill={colors[i]}
        />
      );
    }
    return charts;
  };

  return (
    <ScatterChart
      width={width}
      height={height - 100}
      margin={{ top: 10, right: 40, bottom: 0, left: 0 }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis
        type="number"
        dataKey="x"
        name="height"
        unit="cm"
        range={[100, 250]}
      />
      <YAxis
        type="number"
        dataKey="y"
        name="width"
        unit="cm"
        range={[200, 300]}
      />
      <ZAxis
        type="number"
        dataKey="z"
        name="weight"
        unit="cm"
        range={[200, 1000]}
      />
      <Tooltip cursor={{ strokeDasharray: '3 3' }} />
      <Legend />
      {drawCharts(data)}
    </ScatterChart>
  );
};

How can I avoid this incorrect legend on resizing the chart?


Solution

  • For anyone who is interested, I found this codepen where we can override the default tooltip by passing a function. https://codepen.io/brockboren/pen/yEaYQo

    So I changed my code:

    <Tooltip cursor={{ strokeDasharray: '3 3' }} />
    

    to

    <Tooltip labelFormatter={() => { return ''; }} cursor={{ strokeDasharray: '3 3' }} />
    

    which solved the issue for me.