javascript-d3How do I create a gauge using d3.js?
Creating a gauge using d3.js is a straightforward process. The following example code block creates a simple gauge with a current value of 50 and a maximum value of 100:
var gauge = d3.select("#gauge")
.append("svg")
.attr("width", 200)
.attr("height", 200);
var radius = Math.min(200, 200) / 2;
var arc = d3.arc()
.innerRadius(radius - 25)
.outerRadius(radius);
var pie = d3.pie()
.value(function(d) { return d; })
.sort(null);
var data = [50, 100 - 50];
var arcs = gauge.selectAll("g.arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + radius + "," + radius + ")");
arcs.append("path")
.attr("fill", "#e8e8e8")
.attr("d", arc);
arcs.append("path")
.attr("fill", "#00bfff")
.attr("d", arc);
This code will create a gauge with a current value of 50 and a maximum value of 100. The code consists of the following parts:
- Select the container element and create an SVG element:
var gauge = d3.select("#gauge") .append("svg") .attr("width", 200) .attr("height", 200);
- Set the radius of the gauge:
var radius = Math.min(200, 200) / 2;
- Create an arc generator function:
var arc = d3.arc() .innerRadius(radius - 25) .outerRadius(radius);
- Create a pie generator function:
var pie = d3.pie() .value(function(d) { return d; }) .sort(null);
- Set the data for the gauge:
var data = [50, 100 - 50];
- Select all elements with class "arc" and bind the data:
var arcs = gauge.selectAll("g.arc") .data(pie(data)) .enter() .append("g") .attr("class", "arc") .attr("transform", "translate(" + radius + "," + radius + ")");
- Append two paths to the arcs to create the background and foreground of the gauge:
arcs.append("path")
.attr("fill", "#e8e8e8")
.attr("d", arc);
arcs.append("path")
.attr("fill", "#00bfff")
.attr("d", arc);
Helpful links
More of Javascript D3
- How do I use the z-index property with d3.js?
- How can I display Unix time using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I install and use D3.js with Yarn?
- How do I set up the x axis in d3.js?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to parse XML data?
- How do I create a flame graph using JS-D3 on Ubuntu?
- How do I use d3.js to implement zooming functionality?
See more codes...