Recharts Scatter Plot with Zoom and Selection

Rohan Bajaj
2 min readJan 23, 2022

--

Recharts currently does not have in-built zoom functionality for any of the plots. Brush is a way around, but I wouldn’t really consider it as an alternate to native zoom.

The idea is to build a Scatter Plot with two requirements:

  1. Ability to select a data point
  2. Ability to zoom-in

Here’s what the final solution looks like:

https://codesandbox.io/s/recharts-scatter-plot-zoom-and-click-v68gk

Scatter Plot With Zoom and Select

Part 1 : Selecting a data point

The easy way to select a data point is using the onClick event handler of Scatter component. However, since we will be using the onMouseDown event to implement zoom functionality in Part 2, let’s try to re-use the same event handler. There are two challenges:

  1. ScatterChart does not have access to the actual data
  2. Determining if the user clicked on a data point or empty white space

For the first part, we use CustomDot in the shape prop of Scatter component. In the CustomDot, we add the actual data to the svg’s data-attributes. And when there’s an onMouseDown event, we retrieve it.

For the second part, we use a simple formula to calculate the distance between the point of mouse down and the point where a CustomDot lies. For every CustomDot we calculate this distance and if it is ≤ the radius of the CustomDot, we can say it was clicked.

Part 2: Adding zoom to the chart

Zoom is inspired by this.

  1. zoomArea: State to hold the zoom coordinates
  2. filteredData: State to hold the filtered data point after zooming-in
  3. isZooming: State which helps manage the additional mouse event handler
  4. onMouseMove: Event where we update the zoomArea coordinates.
  5. onMouseUp: Event where we filter the data based on new zoom

Hopefully this solution will suffice until @recharts launches the in-built zoom! Thanks for reading!

--

--