Create a Stacked Area Chart using Recharts in ReactJS
RechartJS is a library that is used for creating charts for ReactJS. This library is used for building Line charts, Bar charts, Pie charts, etc with the help of React and D3 (Data-Driven Documents).
Stacked Area Chart is the extension of a basic area chart. It displays various continuous data in the same area chart for a better comparison of data. An area chart combines the line chart and bar chart to demonstrate numeric value deviation over a certain progressive variable.
Approach: To create a Stacked Area Chart we use AreaChart component of recharts npm package. We firstly create a cartesian grid and X-axis and Y-Axis. Then add multiple Area chart using Area component and get them stacked on top of each other. We use the same stackId for all charts.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example 1: Here, we will create a basic stacked Area chart using AreaChart and Area component of recharts npm package. To stack the two area chart component on top of each other we will add the same stackId to both Area components.
Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Example 2: Here, to convert this from an area chart to a curved graph we will set the type property to monotone. And if we want area charts to stack on top of each other and third to overlap them instead of stacking we will give different stack id to one which needs to overlap and the same to those which have to be stacked.
Now change the following code in the App.js file.
Output: Save the project using CTRL+S.Now open your browser and go to http://localhost:3000/, you will see the following output: