Skip to content

Instantly share code, notes, and snippets.

@jwdomingo
Last active August 29, 2015 14:18
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 jwdomingo/d7d2a2df1e307d078107 to your computer and use it in GitHub Desktop.
Save jwdomingo/d7d2a2df1e307d078107 to your computer and use it in GitHub Desktop.
Rainy Days
<!DOCTYPE html>
<html>
<head>
<title>RainyDays | A d3.js Visualization by John Domingo</title>
<meta charset="UTF-8">
<script type="text/javascript" src="d3/d3.v3.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
div {
max-width: 98%;
margin: 0 auto;
display: block;
}
/* svg {
position: fixed;
display: block;
bottom: 0;
} */
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
function responsivefy(svg) {
// get container + svg aspect ratio
var container = d3.select(svg.node().parentNode),
width = parseInt(svg.style("width")),
height = parseInt(svg.style("height")),
aspect = width / height;
// add viewBox and preserveAspectRatio properties,
// and call resize so that svg resizes on inital page load
svg.attr("viewBox", "0 0 " + width + " " + height)
.attr("perserveAspectRatio", "xMinYMid")
.call(resize);
// to register multiple listeners for same event type,
// you need to add namespace, i.e., 'click.foo'
// necessary if you call invoke this function for multiple svgs
// api docs: https://github.com/mbostock/d3/wiki/Selections#on
d3.select(window).on("resize." + container.attr("id"), resize);
// get width of container and resize svg to fit it
function resize() {
var targetWidth = parseInt(container.style("width"));
svg.attr("width", targetWidth);
svg.attr("height", Math.round(targetWidth / aspect));
}
}
var w = 700;
var h = 400;
var minBar = 5;
var padding = 1;
var dataset = [];
for (var i = 0; i < 25; i++) {
var newNum = (Math.random() * (h / 11 - minBar + 1)) + minBar;
dataset.push(newNum);
}
//var dataset = [ 5, 10, 15, 20, 25 ];
var svg = d3.select("div").append("svg")
.attr({
width: w,
height: h
})
.call(responsivefy);
var bars = svg.selectAll("rect")
.data(dataset)
.enter().append("rect");
bars.attr({
x: function(d, i) {
return i * (w / dataset.length); },
y: function(d, i) {
return h - (d * 10); },
width: function(d, i) {
return (w / dataset.length) - padding; },
height: function(d) {
return (d * 10); },
fill: function(d) {
return "rgb(255," + Math.floor(d * 6) + ",150)";
}
});
svg.selectAll("text")
.data(dataset)
.enter().append("text")
.text(function(d) {
return Math.floor(d * 10);
})
.attr({
"font-family": "sans-serif",
"font-size": "11px",
fill: "white",
x: function(d, i) {
var barH = Math.floor(d * 10);
if (barH < 100) {
return i * (w / dataset.length) + 7.5;
} else {
return i * (w / dataset.length) + 4.5;
}
},
y: function(d, i) {
return h - (d * 10) + 15; }
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment