Data Visualization is an important technique for web applications whether you are building a dashboard, analytics tools or any application that works on data (data-driven application) because it helps us to present the data in a way which is understandable and visually appealing. Developers often look for powerful chart libraries that simplify the process of creating stunning visualizations without much effort.
In this article, our primary focus will be React charts and it’s powerful libraries available to enhance your data visualization capabilities.
Table of Contents
- What are React Libraries?
- Why we need React Chart Libraries?
- ApexCharts
- Recharts
- React-Chartjs-2
- Victory
- React-vis
- React Google Charts
- React Stockcharts
- Nivo
- React FusionCharts
- Visx
What are React Libraries?
React libraries are collections of pre-built components, functions, and tools designed to simplify and enhance the development process in React applications. React itself is a popular JavaScript library used for building user interfaces, but it provides only the core functionalities for managing the UI and state. React libraries, on the other hand, extend React’s capabilities by offering ready-to-use solutions for common tasks and challenges faced during web development.
These React Components libraries are created by developers and organizations to address specific needs, improve code reusability, and boost productivity. They follow the “don’t reinvent the wheel” philosophy, allowing developers to focus on building the unique aspects of their applications without wasting time on repetitive tasks.
Key Features
- Pre-designed and pre-built UI components for easy integration.
- Promotes code reusability and consistency in design.
- Customizable components to match the application’s branding and design.
- Responsive design capabilities for various screen sizes and devices.
- Accessibility-focused, following accessibility guidelines.
- Performance optimization for efficient rendering.
- Large and active community support for documentation and issue resolution.
- Reduces the chances of UI bugs and inconsistencies with well-tested and proven components.
- Supports theming and styling options for seamless integration with different design systems.
Why we need React Chart Libraries?
Now you might wonder why do we need chart libraries? Let’s imagine you have lots of data, such as numbers or statistics, which could be related to anything like your product sales or user data. Now, you want to showcase that data to someone. Yes, you can send those tables and long lists, which can be boring, if I am being honest. Nobody has the time to look through your Excel sheet. So, the best way is to convert this data into beautiful charts because they are easy to read and pleasant to the eyes.
That’s where these React Chart libraries come into play, they make it easier for developers to create these charts without starting from scratch. These libraries contain various types of charts such as Bar chart, Line chart, Pie chart, Area chart, Scatter plot, Bubble chart, Radar chart, Histogram, Box plot and many more. You just have to customize these according to your project’s needs. This saves a lot of time and effort for developers who may not have specialized knowledge in designing charts.
Charts are valuable tools because they enable people to easily understand patterns, trends, and connections within the data. For example, a bar chart is best for comparing different categories, whereas a line chart helps us visualize changes over time. By using react component libraries, developers can focus more on business logic rather than reinventing UI components.
As you can see in the above image, on one side, there is plain and boring data, while on the other hand, there’s modern visualization using charts. Now, which one do you think looks better and would reach a broader audience?
Advantages
- Easy and accessible and make data visualization easy.
- Support multiple chart types
- Provide customization of Colors, sizes, labels, tooltips, animations etc.
- Seamless React integration.
- Optimized for performance with small bundle size.
- Automatically update charts when data changes.
- Export Allow exporting charts to images like PNG, JPEG SVG.
- Charts components can be reused across your app, reducing duplication of code.
- Chart libraries are designed to scale to handle large datasets efficiently.
Now, let’s dive into the world of React charts libraries and take a look at the top 10 options. Each library comes with its own unique set of features and use cases, making the process easier and more efficient. Let’s explore!
ApexCharts
ApexCharts is a modern charting library that helps developers to create beautiful and interactive visualizations for web pages. It is an open-source project licensed under MIT and is free to use in commercial applications.
ApexCharts allows you to create responsive charts that scale well for different screen sizes like desktops, tablets and mobile phones. You can define responsive queries to have different chart layouts for different screen widths. This ensures a good user experience across devices.
The charts are highly interactive. Users can zoom, pan and scroll through the data. They can toggle the visibility of datasets in multi-series charts. When users hover over data points, informative tooltips are shown. All these interactions help communicate the data more effectively.
ApexCharts can load data dynamically based on user selections and then create other dependent charts based on that data. This makes the charts truly interactive as data can be updated in real time based on user actions.
The charts provide high performance, especially for large datasets with thousands of data points. ApexCharts uses optimizations and caching techniques to render charts quickly and smoothly.
Annotations can be added to charts to clarify things for users. Labels can be placed on axes or specific data points to highlight important values or events. This aids in interpreting the charts easily.
Features
- ApexCharts scales well for different screen sizes and aspect ratios.
- Interactive features like zooming, panning, and real-time updates.
- It can handle dynamic data and update the chart accordingly.
- Renders large datasets efficiently using caching techniques.
- Annotate charts by placing labels on axes and data points.
- Smoothly changes datasets, loads dynamic data and interacts with charts.
We have used ApexCharts in out Modernize React MUI Dashboard Theme. You can check out the live preview.
It is the most powerful and developer friendly React Admin Dashboard template based on MUI React Library, That helps you to kickstart your web app project with its customizability and feature / pages options. It has more than 13 Applications which are ready to use such as Calendar App, Chat App, E-Commerce Shop App and many others.
How to use ApexCharts?
- Install the ApexCharts using the following command:
npm install react-apexcharts --save
# or
yarn add react-apexcharts
- Then import the component and start using it:
import React, { Component } from "react";
import Chart from "react-apexcharts";
class App extends Component {
constructor(props) {
super(props);
this.state = {
options: {
chart: {
id: "basic-bar"
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
}
},
series: [
{
name: "series-1",
data: [30, 40, 45, 50, 49, 60, 70, 91]
}
]
};
}
render() {
return (
<div className="app">
<div className="row">
<div className="mixed-chart">
<Chart
options={this.state.options}
series={this.state.series}
type="bar"
width="500"
/>
</div>
</div>
</div>
);
}
}
export default App;
You can see the preview in the following Code Sandbox:
Recharts
Recharts is another React charting library that simplifies creating charts by providing a wide range of chart components out of the box. It is built on top of D3.js but abstracts away the complexities, making it easier for React developers to create interactive and visually appealing charts and graphs. Recharts leverage the power of SVG (Scalable Vector Graphics) for rendering, allowing charts to be scalable and fit on any screen size.
The main purpose of this library is to help you to write charts in React applications without any pain. Main principles of Recharts are:
- Simply deploy with React components.
- Native SVG support, lightweight depending only on some D3 submodules.
- Declarative components, components of charts are purely presentational.
Features
- A rich collection of chart types and customization options.
- Animation and interaction support for seamless user experiences.
- Responsive design for various devices and screen sizes.
- Straightforward integration with React applications.
- The library has a lightweight bundle size – Around 8KB minified.
- You have full control over chart styling using the theme object. You can customize colors, font styles, sizes, paddings, etc.
How to use Recharts?
- Install Recharts using the following command:
npm install recharts
# or
yarn add recharts
- Then import the component and use it:
import React from "react";
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
} from "recharts";
const data = [
{
name: "Page A",
uv: 4000,
pv: 2400,
amt: 2400,
},
{
name: "Page B",
uv: 3000,
pv: 1398,
amt: 2210,
},
{
name: "Page C",
uv: 2000,
pv: 9800,
amt: 2290,
},
{
name: "Page D",
uv: 2780,
pv: 3908,
amt: 2000,
},
//...more data
];
export default function App() {
return (
<AreaChart
width={500}
height={400}
data={data}
margin={{
top: 10,
right: 30,
left: 0,
bottom: 0,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Area
type="monotone"
dataKey="uv"
stackId="1"
stroke="#8884d8"
fill="#8884d8"
/>
<Area
type="monotone"
dataKey="pv"
stackId="1"
stroke="#82ca9d"
fill="#82ca9d"
/>
<Area
type="monotone"
dataKey="amt"
stackId="1"
stroke="#ffc658"
fill="#ffc658"
/>
</AreaChart>
);
}
You can see the preview in the following Code Sandbox:
React-Chartjs-2
If you’ve heard of Chart.js, you might wonder what React-chartjs-2 is all about. Well, think of it as a handy tool for using Chart.js within your React projects. Chart.js is a JavaScript library that helps create various types of interactive charts using HTML5 Canvas.
React-chartjs-2 acts like a bridge, making it easier to use Chart.js in React. If you’re already familiar with Chart.js, adopting React-chartjs-2 should be straightforward. It’s a beginner-friendly React chart library with lots of unique chart components.
While react-chartjs-2 doesn’t have it’s own detailed documentation, its website provides insights into different chart types and how to begin using them. In addition, Chart.js offers detailed and user-friendly documentation to support your charting needs.
Features
- Supports various chart types: line, bar, pie, doughnut, radar, and more.
- Declarative syntax for easy configuration.
- Interactive charts with tooltips and clickable legends.
- Dynamic updates for changing data.
- Extensive customization options for appearance and behavior.
- Responsive design for different screen sizes.
- Compatible with Server-Side Rendering (SSR).
- Active maintenance and strong community support.
How to use react-chartjs-2?
- Install the chart.js and react-chartjs-2 first using the following command:
npm install --save chart.js react-chartjs-2
# or
yarn add chart.js react-chartjs-2
- Then, import and use individual components:
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
ChartJS.register(ArcElement, Tooltip, Legend);
<Doughnut data={...} />
You can see the preview in the Code Sandbox.
Victory
Victory is a set of modular charting components for React and React Native. Victory makes it easy to get started without sacrificing flexibility. Create one of a kind data visualizations with fully customizable styles and behaviors. Victory uses the same API for web and React Native applications for easy cross-platform charting.
It is also known for its detailed documentation, making it user-friendly and perfect for beginners to dive into. The library supports SVG drawing and provides high-quality customizable animations. This library is unique because it can be used to build both iOS and Android apps.
Features
- A collection of pre-built, customizable chart components.
- Comprehensive documentation and active community support.
- Robust event system for handling interactions.
- Integrates smoothly with React apps.
- Support for Android and iOS apps.
- Supports drawing with SVG.
- High-quality customizable animations.
How to use Victory?
- Install victory by using the following command:
npm install victory --save
# or
yarn add victory
- Then, import and use it’s components:
import React, { Component } from "react";
import { render } from "react-dom";
import { VictoryPie } from "victory";
class PieChart extends Component {
const data = [
{ x: "Cats", y: 35 },
{ x: "Dogs", y: 40 },
{ x: "Birds", y: 55 }
]
render() {
return <VictoryPie data={data} />;
}
}
render(<PieChart />, document.getElementById("app"));
You can see the preview in the following Code Sandbox:
React-vis
React-vis is a user-friendly React visualization library that adheres to the core principles of React development. It seamlessly integrates with other React components, allowing you to work with it effortlessly. With properties, children, and callbacks, React-vis components can be easily composed, making it accessible even to React beginners. It was created by Uber and built with React and D3.
It is not just a theoretical concept; it has been tested and utilized within Uber’s internal tools, showcasing its strength and reliability in real-world applications. Therefore, users can rest assured that React-vis is not only user-friendly but also industry-strong, ready to support their data visualization.
Features
- Simplified API for easy integration with React apps.
- Basic chart types like bar, line, and scatter plots.
- Supports real-time data updates.
- Active community and good documentation.
- Supports a wide range of charts, from area charts to treemaps.
- Smooth animations for better user experience.
- Lightweight and easy to use.
- Optimized for rendering large datasets efficiently.
How to use React-vis?
- Install react-vis by using the following command:
npm install react-vis --save
# or
yarn add react-vis
- Then, import and use it’s components:
import React, { Component } from 'react';
import './App.css';
import '../node_modules/react-vis/dist/style.css';
import {XYPlot, LineSeries} from 'react-vis';
class App extends Component {
render() {
const data = [
{x: 0, y: 8},
{x: 1, y: 5},
{x: 2, y: 4},
{x: 3, y: 9},
{x: 4, y: 1},
{x: 5, y: 7},
{x: 6, y: 6},
{x: 7, y: 3},
{x: 8, y: 2},
{x: 9, y: 0}
];
return (
<div className="App">
<XYPlot height={300} width={300}>
<LineSeries data={data} />
</XYPlot>
</div>
);
}
}
export default App;
You can see the preview in the following Code Sandbox:
React Google Charts
React Google Charts is a library that allows you to easily embed Google Charts (such as Bar Charts, Line Charts, Pie Charts, Geo Charts, etc.) into your React applications.
It works by wrapping the Google Charts JavaScript API into React components. This allows you to create charts in React, where the charts’ data and configuration are passed as props to the chart components.
You can also create 3D charts with options like {is3D: true}
. This adds an extra dimension to the visualizations.
Features
- React Google Charts is a library that allows easy integration of Google Charts in React applications.
- Provides a set of React components to render different types of Google Charts, such as line charts, bar charts, pie charts, and more.
- Enables interactive and responsive charts with built-in event handling capabilities.
- Supports a wide range of chart customization options, including colors, fonts, tooltips, and legends.
- Facilitates dynamic data updates, allowing real-time chart rendering based on changing data.
- Offers seamless integration with React applications, making use of React’s virtual DOM for efficient rendering.
- Provides consistent charting experience, as it leverages Google Charts API behind the scenes.
- Offers extensive documentation and a vibrant community for support and troubleshooting.
- Compatible with modern web development practices and can be easily integrated with other React libraries and frameworks.
How to use React Google Charts?
- Install react-google-charts by using the following command:
npm install --save react-google-charts
# or
yarn add react-google-charts
- Then, import and use it:
import React from "react";
import { Chart } from "react-google-charts";
export const data = [
["Country", "Popularity"],
["Germany", 200],
["United States", 300],
["Brazil", 400],
["Canada", 500],
["France", 600],
["RU", 700],
];
export function App() {
return (
<Chart
chartEvents={[
{
eventName: "select",
callback: ({ chartWrapper }) => {
const chart = chartWrapper.getChart();
const selection = chart.getSelection();
if (selection.length === 0) return;
const region = data[selection[0].row + 1];
console.log("Selected : " + region);
},
},
]}
chartType="GeoChart"
width="100%"
height="400px"
data={data}
/>
);
}
You can see the preview in the following Code Sandbox:
React Stockcharts
React Stockcharts is an open source library for creating interactive financial charts and technical indicators in React applications. It is built on top of d3-financial, which is a D3 extension for finance.
The library enables you to create various financial charts, such as Candlestick charts, Line charts, Bar charts, OHLC charts, and many more. It also supports rendering over 50+ technical indicators like:
- MACD
- RSI
- Stochastic Oscillator
- Moving Averages
- Bollinger Bands
You can find the full list here. You can render these charts and indicators by creating React components and passing the data as a prop. The library takes care of updating the chart and re-rendering it whenever the data changes.
Features
- Renders candlestick charts, line charts, OHLC charts, volume charts, Heikin-Ashi charts and more
- Supports over 50+ technical indicators like MACD, RSI, Bollinger Bands, Moving Averages etc.
- Charts re-render automatically when data changes
- Modular chart components for reusability
- Extensible and customizable charts
- Optimized using d3-finance under the hood
- Interactive charts with zooming, panning and tooltips
- Provides a comprehensive charting library for building financial apps in React
How to use?
- Install the react-stockcharts by using the following command:
npm install --save react-stockcharts
# or
yarn add react-stockcharts
- Import the Component and start using it:
// index.js
import React from 'react';
import { render } from 'react-dom';
import Chart from './Chart';
import { getData } from "./utils"
import { TypeChooser } from "react-stockcharts/lib/helper";
class ChartComponent extends React.Component {
componentDidMount() {
getData().then(data => {
this.setState({ data })
})
}
render() {
if (this.state == null) {
return <div>Loading...</div>
}
return (
<TypeChooser>
{type => <Chart type={type} data={this.state.data} />}
</TypeChooser>
)
}
}
render(
<ChartComponent />,
document.getElementById("root")
);
- Define the Chart:
// Chart.js
import React from "react";
import PropTypes from "prop-types";
import { scaleTime } from "d3-scale";
import { format } from "d3-format";
import { timeFormat } from "d3-time-format";
import { ChartCanvas, Chart } from "react-stockcharts";
import {
BarSeries,
CandlestickSeries,
} from "react-stockcharts/lib/series";
import { XAxis, YAxis } from "react-stockcharts/lib/axes";
import {
CrossHairCursor,
EdgeIndicator,
CurrentCoordinate,
MouseCoordinateX,
MouseCoordinateY,
} from "react-stockcharts/lib/coordinates";
import { OHLCTooltip } from "react-stockcharts/lib/tooltip";
import { fitWidth } from "react-stockcharts/lib/helper";
import { last } from "react-stockcharts/lib/utils";
class CandleStickChartForContinuousIntraDay extends React.Component {
render() {
const { type, data, width, ratio } = this.props;
const xAccessor = d => d.date;
const start = xAccessor(last(data));
const end = xAccessor(data[Math.max(0, data.length - 150)]);
const xExtents = [start, end];
return (
<ChartCanvas height={400}
ratio={ratio}
width={width}
margin={{ left: 80, right: 80, top: 10, bottom: 30 }}
type={type}
seriesName="MSFT"
data={data}
xScale={scaleTime()}
xAccessor={xAccessor}
xExtents={xExtents}>
<Chart id={2}
yExtents={[d => d.volume]}
height={150} origin={(w, h) => [0, h - 150]}>
<YAxis axisAt="left" orient="left" ticks={5} tickFormat={format(".2s")}/>
<MouseCoordinateY
at="left"
orient="left"
displayFormat={format(".4s")} />
<BarSeries yAccessor={d => d.volume} fill={d => d.close > d.open ? "#6BA583" : "#FF0000"} />
<CurrentCoordinate yAccessor={d => d.volume} fill="#9B0A47" />
<EdgeIndicator itemType="first" orient="left" edgeAt="left"
yAccessor={d => d.volume} displayFormat={format(".4s")} fill="#0F0F0F"/>
<EdgeIndicator itemType="last" orient="right" edgeAt="right"
yAccessor={d => d.volume} displayFormat={format(".4s")} fill="#0F0F0F"/>
</Chart>
<Chart id={1}
yExtents={[d => [d.high, d.low]]}
padding={{ top: 40, bottom: 20 }}>
<XAxis axisAt="bottom" orient="bottom"/>
<YAxis axisAt="right" orient="right" ticks={5} />
<MouseCoordinateX
rectWidth={60}
at="bottom"
orient="bottom"
displayFormat={timeFormat("%H:%M:%S")} />
<MouseCoordinateY
at="right"
orient="right"
displayFormat={format(".2f")} />
<CandlestickSeries />
<EdgeIndicator itemType="last" orient="right" edgeAt="right"
yAccessor={d => d.close} fill={d => d.close > d.open ? "#6BA583" : "#FF0000"}/>
<OHLCTooltip origin={[-40, 0]} xDisplayFormat={timeFormat("%Y-%m-%d %H:%M:%S")}/>
</Chart>
<CrossHairCursor />
</ChartCanvas>
);
}
}
CandleStickChartForContinuousIntraDay.propTypes = {
data: PropTypes.array.isRequired,
width: PropTypes.number.isRequired,
ratio: PropTypes.number.isRequired,
type: PropTypes.oneOf(["svg", "hybrid"]).isRequired,
};
CandleStickChartForContinuousIntraDay.defaultProps = {
type: "svg",
};
CandleStickChartForContinuousIntraDay = fitWidth(CandleStickChartForContinuousIntraDay);
export default CandleStickChartForContinuousIntraDay;
You can see the preview in the following Code Sandbox:
Nivo
Nivo is a data visualization library built on top of D3.js and React. It offers a range of well-designed, customizable charts with great animations, making it suitable for creating visually impressive data visualizations.
It provides an innovative solution for web developers to generate charts and data visualizations on the server side. It also offers a wide variety of templates and designs for charts that developers can choose from. The charts have a distinctive look and effectively convey data in an impactful way.
Several libraries already exist for React d3 integration, but just a few provide server side rendering ability and fully declarative charts.
Features
- Highly customizable
- Motion/transitions, powered by @react-spring
- Component playground
- Exhaustive documentation
- Isomorphic rendering
- SVG charts
- HTML charts
- Canvas charts
- Server side rendering API
- Legends
- SVG patterns
- Gradients
- Responsive charts
How to use nivo?
- Install the nivo by using the following command
# core package
npm install @nivo/core
# for bar charts
npm install @nivo/bar
# for bump chart
npm install @nivo/bump # we have used bump in our example
- Import the Component and start using it:
import { ResponsiveBump } from '@nivo/bump'
const data = [
{
"id": "Serie 1",
"data": [
{
"x": 2000,
"y": 5
},
{
"x": 2001,
"y": 8
},
{
"x": 2002,
"y": 6
},
{
"x": 2003,
"y": 5
},
{
"x": 2004,
"y": 1
}
]
},
// ... more data
];
const MyResponsiveBump = () => (
<ResponsiveBump
data={data}
colors={{ scheme: 'spectral' }}
lineWidth={3}
activeLineWidth={6}
inactiveLineWidth={3}
inactiveOpacity={0.15}
pointSize={10}
activePointSize={16}
inactivePointSize={0}
pointColor={{ theme: 'background' }}
pointBorderWidth={3}
activePointBorderWidth={3}
pointBorderColor={{ from: 'serie.color' }}
axisTop={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: '',
legendPosition: 'middle',
legendOffset: -36
}}
axisBottom={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: '',
legendPosition: 'middle',
legendOffset: 32
}}
axisLeft={{
tickSize: 5,
tickPadding: 5,
tickRotation: 0,
legend: 'ranking',
legendPosition: 'middle',
legendOffset: -40
}}
margin={{ top: 40, right: 100, bottom: 40, left: 60 }}
axisRight={null}
/>
)
You can see the preview in the following Code Sandbox:
React FusionCharts
React FusionCharts is a JavaScript charting library that enables you to create interactive charts, gauges, maps and dashboards in JavaScript. We have built a simple and lightweight React component that provides bindings for FusionCharts. The react-fusioncharts
component allows you to easily add rich and interactive charts to any React project.
FusionCharts offers a wide range of chart types like bar charts, pie charts, line charts, area charts, funnel charts, radar charts, maps, gauges, and more. It has over 2000 maps covering countries, states, and cities that you can plot data on.
Features:
- React FusionCharts is a React wrapper for FusionCharts, enabling seamless integration of interactive charts into React applications.
- Offers various chart types, such as line, area, bar, column, and more.
- This software:
- Has many options for customizing colors, fonts, labels, tooltips, and animations.
- Can render data in real-time and dynamically update charts based on changing data.
- Makes data binding and integration with various sources, such as JSON, XML, and CSV, easy.
- Allows users to interact with charts by zooming, panning, drilling-down, and using tooltips.
- Includes various themes to quickly change the chart’s appearance and style to match the application’s design.
How to use React Fusion Charts?
- Install fusioncharts and react-fusioncharts by using the following command:
npm install fusioncharts react-fusioncharts --save
# or
yarn add fusioncharts react-fusioncharts
- Import components and prepare the data and configuration, then start using it.
// STEP 1 - Include Dependencies
// Include react
import React from "react";
import ReactDOM from "react-dom";
// Include the react-fusioncharts component
import ReactFC from "react-fusioncharts";
// Include the fusioncharts library
import FusionCharts from "fusioncharts";
// Include the chart type
import Column2D from "fusioncharts/fusioncharts.charts";
// Include the theme as fusion
import FusionTheme from "fusioncharts/themes/fusioncharts.theme.fusion";
// Adding the chart and theme as dependency to the core fusioncharts
ReactFC.fcRoot(FusionCharts, Column2D, FusionTheme);
// STEP 2 - Chart Data
const chartData = [
{
label: "Venezuela",
value: "290"
},
{
label: "Saudi",
value: "260"
},
{
label: "Canada",
value: "180"
},
{
label: "Iran",
value: "140"
},
{
label: "Russia",
value: "115"
},
{
label: "UAE",
value: "100"
},
{
label: "US",
value: "30"
},
{
label: "China",
value: "30"
}
];
// STEP 3 - Creating the JSON object to store the chart configurations
const chartConfigs = {
type: "column2d", // The chart type
width: "700", // Width of the chart
height: "400", // Height of the chart
dataFormat: "json", // Data type
dataSource: {
// Chart Configuration
chart: {
//Set the chart caption
caption: "Countries With Most Oil Reserves [2017-18]",
//Set the chart subcaption
subCaption: "In MMbbl = One Million barrels",
//Set the x-axis name
xAxisName: "Country",
//Set the y-axis name
yAxisName: "Reserves (MMbbl)",
numberSuffix: "K",
//Set the theme for your chart
theme: "fusion"
},
// Chart Data
data: chartData
}
};
// STEP 4 - Creating the DOM element to pass the react-fusioncharts component
class App extends React.Component {
render() {
return (<ReactFC {...chartConfigs} />);
}
}
export default App;
You can see the preview in the following Code Sandbox:
Visx
Visx is a React-based library used for constructing data visualizations. It comprises a set of reusable, low-level visualization components that merge the power of D3 for data transformation and calculations with the benefits of React for updating the DOM.
It is not a complete visualization library, but a collection of primitives and components that can be mixed and matched to create custom charts and visualizations. It is component-based and unopinionated, making it lightweight and flexible. You can import only the necessary components. It focuses on performance, learnability, and expressivity. It’s easy for React developers to learn.
Its packages include shapes, grids, axes, scales, tooltips, legends, and responsiveness. It was built by Airbnb.
Features:
- Visx is a powerful data visualization library for React that offers customizable chart components.
- Provides various chart types, including bar, line, area, and pie charts.
- Integrates smoothly with React applications for efficient rendering and updates.
- Allows extensive customization of colors, styles, and annotations for visually appealing charts.
- Supports smooth and interactive animations to enhance the user experience.
- Facilitates data transformation and manipulation for different chart requirements.
- Enables the creation of complex and dynamic charts through component composability.
- Offers excellent performance and responsiveness, even with large datasets.
- Provides detailed documentation and examples for easy learning.
- Can be easily integrated with other popular React libraries and frameworks.
How to use visx?
- Install the following dependencies:
npm install --save yarn add @visx/shape @visx/group @visx/grid @visx/axis @visx/scale @visx/tooltip @visx/legend @visx/responsive
# or
yarn add @visx/shape @visx/group @visx/grid @visx/axis @visx/scale @visx/tooltip @visx/legend @visx/responsive
- Import all the components and data and start using it:
import React, { useRef, useState, useEffect } from 'react';
import { Group } from '@visx/group';
import { LineRadial } from '@visx/shape';
import { scaleTime, scaleLog, NumberLike } from '@visx/scale';
import { curveBasisOpen } from '@visx/curve';
import appleStock, { AppleStock } from '@visx/mock-data/lib/mocks/appleStock';
import { LinearGradient } from '@visx/gradient';
import { AxisLeft } from '@visx/axis';
import { GridRadial, GridAngle } from '@visx/grid';
import { animated, useSpring } from '@react-spring/web';
const green = '#e5fd3d';
export const blue = '#aeeef8';
const darkgreen = '#dff84d';
export const background = '#744cca';
const darkbackground = '#603FA8';
const strokeColor = '#744cca';
const springConfig = {
tension: 20,
};
// utils
function extent<Datum>(data: Datum[], value: (d: Datum) => number) {
const values = data.map(value);
return [Math.min(...values), Math.max(...values)];
}
// accessors
const date = (d: AppleStock) => new Date(d.date).valueOf();
const close = (d: AppleStock) => d.close;
const formatTicks = (val: NumberLike) => String(val);
// scales
const xScale = scaleTime({
range: [0, Math.PI * 2],
domain: extent(appleStock, date),
});
const yScale = scaleLog<number>({
domain: extent(appleStock, close),
});
const angle = (d: AppleStock) => xScale(date(d)) ?? 0;
const radius = (d: AppleStock) => yScale(close(d)) ?? 0;
const padding = 20;
const firstPoint = appleStock[0];
const lastPoint = appleStock[appleStock.length - 1];
export type LineRadialProps = {
width: number;
height: number;
animate?: boolean;
};
function Example({ width, height, animate = true }: LineRadialProps) {
const lineRef = useRef<SVGPathElement>(null);
const [lineLength, setLineLength] = useState<number>(0);
const [shouldAnimate, setShouldAnimate] = useState<boolean>(false);
const spring = useSpring({
frame: shouldAnimate ? 0 : 1,
config: springConfig,
onRest: () => setShouldAnimate(false),
});
// set line length once it is known after initial render
const effectDependency = lineRef.current;
useEffect(() => {
if (lineRef.current) {
setLineLength(lineRef.current.getTotalLength());
}
}, [effectDependency]);
if (width < 10) return null;
// Update scale output to match component dimensions
yScale.range([0, height / 2 - padding]);
const reverseYScale = yScale.copy().range(yScale.range().reverse());
const handlePress = () => setShouldAnimate(true);
return (
<>
{animate && (
<>
<button type="button" onClick={handlePress} onTouchStart={handlePress}>
Animate
</button>
<br />
</>
)}
<svg width={width} height={height} onClick={() => setShouldAnimate(!shouldAnimate)}>
<LinearGradient from={green} to={blue} id="line-gradient" />
<rect width={width} height={height} fill={background} rx={14} />
<Group top={height / 2} left={width / 2}>
<GridAngle
scale={xScale}
outerRadius={height / 2 - padding}
stroke={green}
strokeWidth={1}
strokeOpacity={0.3}
strokeDasharray="5,2"
numTicks={20}
/>
<GridRadial
scale={yScale}
numTicks={5}
stroke={blue}
strokeWidth={1}
fill={blue}
fillOpacity={0.1}
strokeOpacity={0.2}
/>
<AxisLeft
top={-height / 2 + padding}
scale={reverseYScale}
numTicks={5}
tickStroke="none"
tickLabelProps={{
fontSize: 8,
fill: blue,
fillOpacity: 1,
textAnchor: 'middle',
dx: '1em',
dy: '-0.5em',
stroke: strokeColor,
strokeWidth: 0.5,
paintOrder: 'stroke',
}}
tickFormat={formatTicks}
hideAxisLine
/>
<LineRadial angle={angle} radius={radius} curve={curveBasisOpen}>
{({ path }) => {
const d = path(appleStock) || '';
return (
<>
<animated.path
d={d}
ref={lineRef}
strokeWidth={2}
strokeOpacity={0.8}
strokeLinecap="round"
fill="none"
stroke={animate ? darkbackground : 'url(#line-gradient)'}
/>
{shouldAnimate && (
<animated.path
d={d}
strokeWidth={2}
strokeOpacity={0.8}
strokeLinecap="round"
fill="none"
stroke="url(#line-gradient)"
strokeDashoffset={spring.frame.interpolate((v) => v * lineLength)}
strokeDasharray={lineLength}
/>
)}
</>
);
}}
</LineRadial>
{[firstPoint, lastPoint].map((d, i) => {
const cx = ((xScale(date(d)) ?? 0) * Math.PI) / 180;
const cy = -(yScale(close(d)) ?? 0);
return <circle key={`line-cap-${i}`} cx={cx} cy={cy} fill={darkgreen} r={3} />;
})}
</Group>
</svg>
</>
);
}
export default Example;
Take a look at the live preview available in the Code Sandbox:
Wrapping up
In conclusion, adding good charts and graphs can really improve how you show data in your React apps. Using the 10 chart libraries mentioned in the article, you can make your data visualizations a lot better.
Each library has its own strengths. Some are easy to use and customize. Others have animations and update in real-time. Whether you have simple or complex data, these libraries can help.
Before choosing a library, think about your needs, how big your app will get, and what design you want. Read the documentation and ask other users to make sure the library will work well for you.
A good chart is worth a thousand words. These libraries have the power to help you make charts that really impress your users. So start charting now and level up how you show data!
Top comments (0)