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.
Circle Chart
We can create a circle chart with D3 in our React app.
For example, we can write:
import React, { useEffect } from "react";
import * as d3 from "d3";
export default function App() {
useEffect(() => {
const width = 400;
const height = 400;
const data = [10, 28, 35];
const colors = ["green", "lightblue", "yellow"];
const svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
const g = svg
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(0,0)";
});
g.append("circle")
.attr("cx", function (d, i) {
return i * 75 + 50;
})
.attr("cy", function (d, i) {
return 75;
})
.attr("r", function (d) {
return d * 1.5;
})
.attr("fill", function (d, i) {
return colors[i];
});
g.append("text")
.attr("x", function (d, i) {
return i * 75 + 25;
})
.attr("y", 80)
.attr("stroke", "teal")
.attr("font-size", "10px")
.attr("font-family", "sans-serif")
.text((d) => {
return d;
});
}, []);
return (
<div className="App">
<div id="svgcontainer"></div>
</div>
);
}
We create the svg by selecting the body and then add the svg to it.
And we also set the width and height of the SVG.
This is done with:
const svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
Then we create the group with the data by writing:
const g = svg
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) {
return "translate(0,0)";
});
data has the data.
Next, we add the circles by writing:
g.append("circle")
.attr("cx", function(d, i) {
return i * 75 + 50;
})
.attr("cy", function(d, i) {
return 75;
})
.attr("r", function(d) {
return d * 1.5;
})
.attr("fill", function(d, i) {
return colors[i];
});
We add the cx and cy attributes by call attr .
r has the radius, and fill has the background color for each circle.
Then we add the text that goes with the circles by writing:
g.append("text")
.attr("x", function(d, i) {
return i * 75 + 25;
})
.attr("y", 80)
.attr("stroke", "teal")
.attr("font-size", "10px")
.attr("font-family", "sans-serif")
.text((d) => {
return d;
});
We call append with the 'text' argument.
And then we set the x and y attributes of the position of the text.
Then we set the color of the text with the stroke .
font-size has the font size and font-family has the font family.
The text method takes a callback that returns the text.
Conclusion
We can add a circle chart into our React app with D3 easily.