Skip to content

Instantly share code, notes, and snippets.

@alansmithy
Last active July 24, 2017 00:49
Show Gist options
  • Save alansmithy/48419ae3f97bee48cbbe52923830acfc to your computer and use it in GitHub Desktop.
Save alansmithy/48419ae3f97bee48cbbe52923830acfc to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var w = 900
var h =560
var margin = {left:30,top:30,right:30,bottom:50}
var plotW = w-(margin.left+margin.right)
var plotH = h-(margin.top+margin.bottom)
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h)
var data=[
{name:"A",val1:30,val2:80},
{name:"B",val1:60,val2:64},
{name:"C",val1:10,val2:25},
{name:"D",val1:25,val2:53},
{name:"E",val1:64,val2:34},
{name:"F",val1:32,val2:29},
]
var chart = svg.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")")
chart.append("rect")
.attr("width",plotW)
.attr("height",plotH)
.attr("fill","skyblue")
var title = svg.append("text")
.text("Population structure of Uruguay, 1950 (%)")
.attr("y", 20)
.attr("x", margin.left)
.attr("font-size", 24)
.attr("font-family", "monospace")
var yScale = d3.scaleLinear()
.domain([0,100])
.range([plotH,0]);
//for the xscale, we want to extract the names of cats
var cats = data.map(function(d){
return d.name
})
var xScale = d3.scaleBand()
.domain(cats)
.range([0,plotW])
.padding(0.2)//adjust spacing between bars
//define axes
const xAxis = d3.axisBottom(xScale)
.tickSizeInner(0)
.tickSizeOuter(0)
const yAxis = d3.axisLeft(yScale)
.ticks(5)
.tickSizeOuter(0)
.tickSizeInner(-plotW);
//render axes
chart.append("g")
.attr("id","xAxis")
.attr("transform","translate("+0+","+plotH+")")
.call(xAxis);
chart.append("g")
.attr("id","yAxis")
.attr("transform","translate("+0+","+0+")")
.call(yAxis);
var rects = chart.append("g").selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("fill","white")
.attr("x",function(d){
return xScale(d.name)
})
.attr("height",function(d){
return plotH-(yScale(d.val1))
})
.attr("width",xScale.bandwidth)
.attr("y",function(d,i){return yScale(d.val1)})
//add a button
svg.append("circle")
.attr("cx",100)
.attr("cy",80)
.attr("r",15)
.attr("fill","yellow")
.on("click",function(){
rects.transition().duration(1000).attr("height",function(d){
return plotH-(yScale(d.val2))
}).attr("y",function(d,i){return yScale(d.val2)})
title.text("Population structure of Uruguay, 2015 (%)")
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment