Introduction to React:
Introduction to D3:
Setting up React:
The easiest way to set up react is by using the create-react-app. To install it globally on your local machine so that it can be reused, run this in your terminal:
npx create react-app react-d3
Next, we change directory into the newly created project:
Setting up D3:
You can add the D3 library to your app either using the CDN or by installing via NPM.In this case, we will be installing using NPM:
npm install d3
To preview the app just created on your default browser, run the code below:
Building charts with D3:
Open the created project with your favorite text editor and navigate to src/App.js. This is the component that is currently rendered in the browser. We would need to remove the content of the render() method so we can replace that with our own content.
In the src folder, create a new js file named BarChart.js. This is where we will build the bar chart that will be rendered. We will use the ComponentDidMount lifecycle method to display the bar chart when the bar chart component has been mounted in the DOM.
When using D3 without React, you do not have to put your D3 code in a method, but this is important in React to ensure that the chart displays only when the component has been mounted on the DOM.
Customization of Charts:
Create SVG Elements using D3:
SVG provides different shapes like lines, rectangles, circles, ellipses, etc. Hence, designing visualizations with SVG gives you more flexibility.
Construct a continuous linear scale where input data (domain) maps to the specified output range.
Array manipulation (array reverse, array sort, array splice)
For geographical projections
- The D3-select() is used to select an HTML element from the document. It selects the first element that matches the argument passed and creates a node for it.
- The append() method appends an HTML node to the selected item and returns a handle to that node.
- The attr() method is used to add attributes to the element. This can be any attribute that you will normally add to the HTML element like class, height, width or fill. Under the SVG variable we created, add the following code:
Create a world.js file, store all the data in JSON format, import this world component in the app folder and use the data.
- We can implement the same for other charts like Linechart, Mapchart, etc
1) Adding Colors to the bar: Legendcolor method is used to add colors to the charts. To use the legendcolor method :
import legendColor from d3-svg-leged
2) Mouse-Over: Implemented events in a chart such as mouseover events. By this event, we can identify each chart’s state color.
MOURITECH PVT LTD