Created
February 10, 2024 17:25
-
-
Save bjpcjp/b07127db7a8d81c6e38f95c134960c75 to your computer and use it in GitHub Desktop.
D3.js - bullet chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; | |
margin: auto; | |
padding-top: 40px; | |
position: relative; | |
width: 800px; | |
} | |
button { | |
position: absolute; | |
right: 40px; | |
top: 10px; | |
} | |
.bullet { font: 10px sans-serif; } | |
.bullet .marker { stroke: #000; stroke-width: 2px; } | |
.bullet .tick line { stroke: #666; stroke-width: .5px; } | |
.bullet .range.s0 { fill: #eee; } | |
.bullet .range.s1 { fill: #ddd; } | |
.bullet .range.s2 { fill: #ccc; } | |
.bullet .measure.s0 { fill: steelblue; } | |
.bullet .title { font-size: 14px; font-weight: bold; } | |
.bullet .subtitle { fill: #999; } | |
</style> | |
<button>Update</button> | |
<script type="text/javascript" src="d3/d3.v3.js"></script> | |
<script src="js/bullet.js"></script> | |
<script> | |
var margin = {top: 5, right: 40, bottom: 20, left: 120}, | |
width = 800 - margin.left - margin.right, | |
height = 50 - margin.top - margin.bottom; | |
var chart = d3.bullet() | |
.width(width) | |
.height(height); | |
d3.json("data/cpu1.json", function(error, data) { | |
var svg = d3.select("body").selectAll("svg") | |
.data(data) | |
.enter().append("svg") | |
.attr("class", "bullet") | |
.attr("width", width + margin.left + margin.right) | |
.attr("height", height + margin.top + margin.bottom) | |
.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")") | |
.call(chart); | |
var title = svg.append("g") | |
.style("text-anchor", "end") | |
.attr("transform", "translate(-6," + height / 2 + ")"); | |
title.append("text") | |
.attr("class", "title") | |
.text(function(d) { return d.title; }); | |
title.append("text") | |
.attr("class", "subtitle") | |
.attr("dy", "1em") | |
.text(function(d) { return d.subtitle; }); | |
d3.selectAll("button").on("click", function() { | |
svg.datum(randomize).call(chart.duration(1000)); | |
}); | |
}); | |
function randomize(d) { | |
if (!d.randomizer) d.randomizer = randomizer(d); | |
d.markers = d.markers.map(d.randomizer); | |
d.measures = d.measures.map(d.randomizer); | |
return d; | |
} | |
function randomizer(d) { | |
var k = d3.max(d.ranges) * .2; | |
return function(d) { | |
return Math.max(0, d + k * (Math.random() - .5)); | |
}; | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment