Creating Grouped Bar Charts in React Using the Visx Library
Written on
Chapter 1: Introduction to the Visx Library
Visx is a powerful library that simplifies the integration of graphics into React applications. This article will guide you through the process of implementing grouped bar charts using Visx.
Section 1.1: Installing Necessary Packages
To build the grouped bar chart, we need to install several essential modules. Begin by executing the following command in your terminal:
npm i @visx/axis @visx/group @visx/mock-data @visx/responsive @visx/scale @visx/shape
This step ensures that all required packages are available for your project.
Section 1.2: Crafting the Chart
We can create our chart by utilizing the items provided by the installed modules. For our example, we'll draw on data from the @visx/mock-data package. Below is a sample implementation:
import React from "react";
import { Group } from "@visx/group";
import { BarGroup } from "@visx/shape";
import { AxisBottom } from "@visx/axis";
import cityTemperature from "@visx/mock-data/lib/mocks/cityTemperature";
import { scaleBand, scaleLinear, scaleOrdinal } from "@visx/scale";
import { timeParse, timeFormat } from "d3-time-format";
const blue = "#aeeef8";
export const green = "#e5fd3d";
const purple = "#9caff6";
export const background = "#612efb";
const data = cityTemperature.slice(0, 8);
const keys = Object.keys(data[0]).filter((d) => d !== "date");
const defaultMargin = { top: 40, right: 0, bottom: 40, left: 0 };
const parseDate = timeParse("%Y-%m-%d");
const format = timeFormat("%b %d");
const formatDate = (date) => format(parseDate(date));
const getDate = (d) => d.date;
const dateScale = scaleBand({
domain: data.map(getDate),
padding: 0.2,
});
const cityScale = scaleBand({
domain: keys,
padding: 0.1,
});
const tempScale = scaleLinear({
domain: [0, Math.max(...data.map((d) => Math.max(...keys.map((key) => Number(d[key])))))],
});
const colorScale = scaleOrdinal({
domain: keys,
range: [blue, green, purple],
});
function Example({ width, height, events = false, margin = defaultMargin }) {
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - margin.bottom;
dateScale.rangeRound([0, xMax]);
cityScale.rangeRound([0, dateScale.bandwidth()]);
tempScale.range([yMax, 0]);
return width < 10 ? null : (
<svg width={width} height={height}>
<Group top={margin.top} left={margin.left}>
<BarGroup
data={data}
keys={keys}
height={yMax}
x0={(d) => getDate(d)}
x0Scale={dateScale}
yScale={cityScale}
color={colorScale}
onClick={(bar) => {
if (events) {
const { key, value } = bar;
alert(JSON.stringify({ key, value }));
}
}}
/>
<AxisBottom
scale={dateScale}
top={yMax}
tickFormat={formatDate}
tickLabelProps={() => ({
fill: green,
fontSize: 11,
textAnchor: "middle",
})}
/>
</Group>
</svg>
);
}
export default function App() {
return (
<div>
<Example width={800} height={400} /></div>
);
}
In this code snippet, we define colors for the bars using the blue, green, and purple variables, and set the background color using background. The data variable contains our mock data to be displayed in the bars, while keys holds the values for the x-axis.
We also create functions for parsing and formatting dates using D3. The dateScale and cityScale handle the respective axes, while tempScale determines the height of the bars, and colorScale assigns colors.
The Example component brings all the elements together. It sets maximum values for the axes based on the provided width and height. The Group component encapsulates the chart elements, mapping barGroups into rectangle elements for visual representation.
Chapter 2: Visual Demonstrations
To further enhance your understanding, here are two videos that demonstrate the concepts discussed:
In the first video, Data Visualization with D3, React, visx and Typescript: 11 - Creating a Bar Chart with visx, you will learn how to build a bar chart effectively using the Visx library.
The second video, Data Visualization with D3, React, visx and Typescript: 12 - Creating a Useful Chart with visx, covers how to create more complex and useful charts with Visx.
Conclusion
Integrating grouped bar charts into your React applications with the Visx library is a straightforward process. If you found this article helpful, consider subscribing to our YouTube channel for more insightful content!