Skip to content

Instantly share code, notes, and snippets.

@codingforpleasure
Last active February 10, 2019 22:27
Show Gist options
  • Save codingforpleasure/72fbc59008c89f1da30dba4b51303f64 to your computer and use it in GitHub Desktop.
Save codingforpleasure/72fbc59008c89f1da30dba4b51303f64 to your computer and use it in GitHub Desktop.
Barchart (provincias, población, censo 2010, Argentina)
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Provincias</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div id="vis"></div>
<script>
var url = "https://raw.githubusercontent.com/aaizemberg/vis/gh-pages/01/data/poblacion.tsv";
d3.tsv(url).then(function(data) {
// console.log(data[0]);
viz( data );
});
function viz( datos ) {
var max = d3.max(datos.map(d => +d.poblacion));
var w = 800, h = 500;
var LasBarrasComienzaAca = 350;
var escala = d3.scaleLinear().domain([0,max]).range([0,w -LasBarrasComienzaAca - 100]);
var svg = d3.select("div#vis").append("svg").attr("width",w).attr("height",h);
svg.selectAll("text.prov")
.data(datos).enter().append("text")
.attr("class","prov")
.attr("text-anchor","end")
.attr("x", LasBarrasComienzaAca - 5)
.attr("y", function(d,i) {return (h/datos.length)*i+11} )
.text(function(d){return d.provincia;})
svg.selectAll("rect")
.data(datos).enter().append("rect")
.attr("fill","white")
.attr("x", LasBarrasComienzaAca )
.attr("y", function(d,i) {return (h/datos.length)*i} )
.attr("height",17)
.attr("width", 0 )
.on("mouseover", function() {
d3.select(this)
.attr("fill", "steelblue");
})
.on("mouseout", function() {
d3.select(this).attr("fill", function() {
return "gray";
});})
.append("title")
.text(function(d,i) {return d.provincia + " tiene " + parseInt(d.poblacion).toLocaleString('es-AR') + " habitantes, según el censo 2010"; });
d3.selectAll("rect")
.transition()
.attr("width", function(d) { return escala(d.poblacion);})
.attr("fill","gray");
svg.selectAll("text.pobla")
.data(datos).enter().append("text")
.attr("class","pobla")
.attr("x", LasBarrasComienzaAca )
.attr("y", function(d,i) {return (h/datos.length)*i+11} )
.text(function(d){return parseInt(d.poblacion).toLocaleString('es-AR');});
d3.selectAll("text.pobla")
.transition()
.duration(5000)
.attr("x", function(d) { return LasBarrasComienzaAca+5+escala(d.poblacion);})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment