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 add a circle into our Vue app with D3.
To do this, we write:
<template>
<div id="app">
<div id="svgcontainer"></div>
</div>
</template>
<script>
import * as d3 from "d3";
import Vue from "vue";
export default {
name: "App",
mounted() {
Vue.nextTick(() => {
const width = 400;
const height = 400;
const data = [10, 24, 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(function (d) {
return d;
});
});
},
};
</script>
We start by creating the constants for the SVG with the width
and height
variables.
The data
has the data we want to display.
colors
have the color for each circle.
We use the width
and height
to create the SVG with:
const svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
Then we add the SVG group g
with:
const g = svg
.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) {
return "translate(0,0)";
});
Then we add the circles with:
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 set the cx
and cy
attributes to add the x and y coordinates of the center of the circles.
Then we add the r
attribute to add the radius. The radius is proportional to the number in data
so if the number is bigger, the radius is bigger.
Then fill
is an entry in the colors
array.
Finally, we add the number display with:
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(function(d) {
return d;
});
The text’s x
and y
attributes are the x and y coordinates of the position of the text.
stroke
has the text color.
font-size
is the size of the font. font-family
is the font type.
text
has a callback that returns the text to display.
Conclusion
We can add a circle chart into our Vue app with D3.