Member-only story

Adding Graphics to a React App with D3 — Scales and Axes

John Au-Yeung
3 min readFeb 4, 2021

--

Photo by Brett Jordan on Unsplash

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

Scales

We can use the scales API to transform data.

For example, we can write:

import React, { useEffect } from "react";
import * as d3 from "d3";
export default function App() {
useEffect(() => {
const data = [100, 220, 330, 350, 400, 250];
const width = 500,
barHeight = 20,
margin = 1;
const scale = d3
.scaleLinear()
.domain([d3.min(data), d3.max(data)])
.range([100, 400]);
const svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", barHeight * data.length);
const g = svg
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function (d, i) {
return `translate(0, ${i * barHeight})`;
});
g.append("rect")
.attr("width", function (d) {
return scale(d);
})
.attr("height", barHeight - margin);

--

--

No responses yet