Skip to content

Instantly share code, notes, and snippets.

@ignorabilis
Last active October 17, 2017 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ignorabilis/1561c2f193983b9ec8aa466d9eb58f16 to your computer and use it in GitHub Desktop.
Save ignorabilis/1561c2f193983b9ec8aa466d9eb58f16 to your computer and use it in GitHub Desktop.
Explore D3 - range chart
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
</body>
</html>
// to view and play just use jsbin - copy the url and replace 'github' with 'jsbin' to instantly view the code in action
// change width and height so that each chart adjusts automatically
// change dataset so that new values are automatically added
var w = 600;
var h = 200;
var padding = 4;
var range_dataset = [{h: 7, r: 4}, {h: 10, r: 5}, {h: 13, r: 10},
{h: 19, r: 7}, {h: 25, r: 15}, {h: 21, r: 8},
{h: 17, r: 16}, {h: 27, r: 10}, {h: 24, r: 22},
{h: 21, r: 8}, {h: 16, r: 14}, {h: 7, r: 7}];
var range_chart = d3.select("body")
.append("div")
.append("svg")
.attr("width", w)
.attr("height", h);
function range_bar_scale(d){
return d * 5;
}
// a "real" range chart
range_chart.selectAll("rect")
.data(range_dataset)
.enter()
.append("rect")
.attrs({
"x": function(d, i){ return i * (w / range_dataset.length); },
"y": function(d, i){ return h - range_bar_scale(d.h); },
"width": function(d, i){ return (w / range_dataset.length) - padding; },
"height": function(d, i){ return range_bar_scale(d.r); },
"fill": function(d, i) { var metric = d.h + d.r;
if (metric <= 32) {
return "#777777";
}
else {
return "#FF2233";
}}
});
range_chart.selectAll("text")
.data(range_dataset)
.enter()
.append("text")
.text(function(d, i){ return d.h + "/" + d.r; })
.attrs({
"text-anchor": "middle",
"x": function(d, i){ return i * (w / range_dataset.length) + (w / range_dataset.length - padding) / 2; },
"y": function(d, i){ return h - range_bar_scale(d.h) + 14; },
"fill": function(d, i) { return "#FFFFFF"; },
"font-family": "sans-serif",
"font-size": 12
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment