javascript-d3How can I create a pie chart using D3 and JavaScript?
Creating a pie chart using D3 and JavaScript is a fairly straightforward process. The following example code will create a basic pie chart using the D3 library:
// Set up the pie chart
var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
// Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
// Create pie chart
var arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
var pie = d3.pie()
.value(function(d) { return d.value; })(data);
var arcs = svg.selectAll("arc")
.data(pie)
.enter()
.append("g")
.attr("class", "arc");
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
This code will create a basic pie chart with the following parts:
- A width and height variable that sets the size of the pie chart.
- An SVG element which is used to contain the pie chart.
- An arc element which defines the shape of the pie chart.
- A pie element which defines the data used to create the pie chart.
- An arcs element which is used to store the individual arcs that make up the pie chart.
- A path element which is used to draw the individual arcs of the pie chart.
Helpful links
More of Javascript D3
- How can I use d3.js with W3Schools?
- How do I set up the x axis in d3.js?
- How do I create a zoomable chart using d3.js?
- How can I display Unix time using d3.js?
- How do I use D3.js to zoom on the x-axis?
- How do I create a zoomable line chart using d3.js?
- How do I use d3.js to zoom to a selected area?
- How can I use D3.js to create interactive visualizations on Udemy?
- How do I implement zooming in a d3.js visualization?
- How can I use d3.js to parse XML data?
See more codes...