Visx is a library that lets us add graphics to our React app easily.
In this article, we’ll look at how to use it to add bar graphs into our React app.
Getting Started
To get started, we’ve to install several modules provided by Visx.,
To install the ones needed by the bar graph, we run:
$ npm install --save @visx/mock-data @visx/group @visx/shape @visx/scale
The @visx/mock-data
library has mock data we can use in our bar graphs.
Create the Bar Graph
To create the bar graph, we add the following code:
import React from "react";
import { letterFrequency } from "@visx/mock-data";
import { Group } from "@visx/group";
import { Bar } from "@visx/shape";
import { scaleLinear, scaleBand } from "@visx/scale";
const data = letterFrequency;
const width = 500;
const height = 300;
const margin = { top: 20, bottom: 20, left: 20, right: 20 };
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - margin.bottom;
const x = (d) => d.letter;
const y = (d) => +d.frequency * 100;
const xScale = scaleBand({
range: [0, xMax],
round: true,
domain: data.map(x),
padding: 0.4
});
const yScale = scaleLinear({
range: [yMax, 0],
round: true,
domain: [0, Math.max(...data.map(y))]
});
const compose = (scale, accessor) => (data) => scale(accessor(data));
const xPoint = compose(xScale, x);
const yPoint = compose(yScale, y);
function BarGraph(props) {
return (
<svg width={width} height={height}>
{data.map((d, i) => {
const barHeight = yMax - yPoint(d);
return (
<Group key={`bar-${i}`}>
<Bar
x={xPoint(d)}
y={yMax - barHeight}
height={barHeight}
width={xScale.bandwidth()}
fill="#fc2e1c"
/>
</Group>
);
})}
</svg>
);
}
export default function App() {
return (
<div>
<BarGraph />
</div>
);
}
data
has the data for our graph.
width
and height
are the width and height of the graph.
margin
has the margins.
xMax
has the max x-axis value.
yMax
has the max y-axis value.
x
is a function to return the data to display for the x-axis.
And y
is the function to return the data to display on the y-axis.
xScale
lets us create the x-axis values to add to the graph.
yScale
has the y-axis values for the graph.
Then we create the compose
function to scale the x and y axis values to fit in the graph.
Once we did that, we create the BarGraph
component with the Group
and Bar
components.
Bar
has the bars.
Group
has the container for the bars.
We set the fill
color for the bar.
And the x
and y
values
y
is set to the height of the bar.
The width
is scaled according to the screen size.
Conclusion
We can add bar graphs easily into our React app with the Visx library.