Skip to content

Instantly share code, notes, and snippets.

@lnmunhoz
Last active February 22, 2019 05:10
Show Gist options
  • Save lnmunhoz/7b32986c535bc2c11f1897ee294bcd80 to your computer and use it in GitHub Desktop.
Save lnmunhoz/7b32986c535bc2c11f1897ee294bcd80 to your computer and use it in GitHub Desktop.
learning d3: scaleBand
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>
const buildingsData = [
{
"name": "Burj Khalifa",
"height": "350"
},
{
"name": "Shanghai Tower",
"height": "263.34"
},
{
"name": "Abraj Al-Bait Clock Tower",
"height": "254.04"
},
{
"name": "Ping An Finance Centre",
"height": "253.20"
},
{
"name": "Lotte World Tower",
"height": "230.16"
}
]
const svg = d3.select("body").append("svg")
.attr("width", 350)
.attr("height", 350)
.style("border", "1px solid black")
const x = d3.scaleBand()
.domain(buildingsData.map(d => d.name))
.range([0, 350])
.paddingInner(0.3)
.paddingOuter(0.3)
const y = d3.scaleLinear()
.domain([0, d3.max(buildingsData, d => d.height)])
.range([0, d3.max(buildingsData, d => d.height)])
const rects = svg.selectAll("rect").data(buildingsData)
rects.enter().append("rect")
.attr("x", (d, i) => x(d.name))
.attr("y", 0)
.attr("width", x.bandwidth)
.attr("height", (d, i) => y(d.height))
.attr("fill", "gray")
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment