Member-only story
Line Chart using React.js d3.js & TypeScript with the help of d3.bisector interaction — Part II
To create interactivity of the mouse following the plotted data there is a need to do a calculation of the closest point to the mouse. Luckily, d3 has a method d3.bisector that can help us with these calculations. In this two-part tutorial, I will show you how to work with d3.bisector.
In the first part of this two-part series, I was working with two linear scale values as the metric and in this part, part two I will be working with value and time metrics using d3.bisector.
I created each tutorial so it can be used as standalone and use the part I, if you need two linear scales as metrics, or part II for time, value metrics.
You can see the final result of this tutorial below;
Setting up your project
I will be using CRA (SPA) using the MHL template to get TS, SCSS, formatting, templates, linting, etc.
$ yarn create react-app bisector --template must-have-libraries
Add d3, d3-cloud and types;
$ yarn add d3 @types/d3
data.csv
A good place to start when working with charts is from the data. The data is made out of three metrics: x, y values, and the date. We will be using here the date as time scale and the y-value.
/public/data/line.csv
x,y,date
1,0.03,1/1/2021
2,0.04,1/2/2021
3,0.06,1/3/2021
4,0.09,1/4/2021
5,0.13,1/5/2021
6,0.18,1/6/2021
7,0.25,1/7/2021
8,0.33,1/8/2021
9,0.45,1/9/2021
...
To creating the components we will be using my templates;
$ npx generate-react-cli component LineChartDateBisector --type=d3WidgetComponent$ npx generate-react-cli component LineChartDateBisectorWidget --type=d3Widget
These templates will create for you the following files we need;
- widgets/LineChartDateBisectorWidget/types.ts
- components/LineChartDateBisector/LineChartDateHelper.tsx
- widgets/LineChartDateBisectorWidget/LineChartDateBisectorWidget.tsx
- components/LineChartDateBisector/…