Adding Pie and Donut Charts to Your React Application Using Visx
Written on
Introduction
In this guide, we will explore how to seamlessly integrate pie and donut charts into your React application using the Visx library.
Installing Necessary Packages
To begin, we need to install several required modules. You can do this by executing the following command:
npm install @visx/gradient @visx/group @visx/mock-data @visx/responsive @visx/scale @visx/shape
Creating Pie and Donut Charts
We can generate pie and donut charts through the following code snippet:
import React, { useState } from "react";
import Pie from "@visx/shape/lib/shapes/Pie";
import { scaleOrdinal } from "@visx/scale";
import { Group } from "@visx/group";
import { GradientPinkBlue } from "@visx/gradient";
import letterFrequency from "@visx/mock-data/lib/mocks/letterFrequency";
import browserUsage from "@visx/mock-data/lib/mocks/browserUsage";
import { animated, useTransition, interpolate } from "react-spring";
Here, we define variables for letters and browser names, which are derived from mock data. This data will be used to render our charts.
The video titled "Pie Charts in React with visx" provides a comprehensive overview of how to create pie charts using the Visx library, making it an excellent resource to accompany this guide.
Next, we create color scales for the pie and donut charts:
const getBrowserColor = scaleOrdinal({
domain: browserNames,
range: [
"rgba(255,255,255,0.7)",
"rgba(255,255,255,0.6)",
"rgba(255,255,255,0.5)",
"rgba(255,255,255,0.4)",
"rgba(255,255,255,0.3)",
"rgba(255,255,255,0.2)",
"rgba(255,255,255,0.1)"
]
});
We also set up state management to track user selections for browsers and letters:
const [selectedBrowser, setSelectedBrowser] = useState(null);
const [selectedAlphabetLetter, setSelectedAlphabetLetter] = useState(null);
The Example component serves as the main container for our charts, where we compute dimensions for rendering based on the provided width and height.
The following code snippet illustrates how we render the pie and donut charts:
<Group>
<Pie
data={browsers}
pieValue={usage}
outerRadius={radius}
innerRadius={radius - donutThickness}
cornerRadius={3}
padAngle={0.005}
>
{(pie) => (
// Render logic for pie chart)}
</Pie>
<Pie
data={letters}
pieValue={frequency}
pieSortValues={() => -1}
outerRadius={radius - donutThickness * 1.3}
>
{(pie) => (
// Render logic for donut chart)}
</Pie>
</Group>
In this setup, we utilize the AnimatedPie component to add animations to our charts.
For further insights, check out the video "Integrate a Donut Pie Chart With Polylines and Labels Utilizing d3js, Reactjs, and TypeScript," which provides valuable techniques for enhancing your charting skills.
Conclusion
With the Visx library, adding pie and donut charts to your React application is straightforward and efficient. By following the steps outlined in this guide, you can create visually appealing charts that effectively communicate data.