Skip to content

Instantly share code, notes, and snippets.

@lnmunhoz
Last active February 22, 2019 05:39
Show Gist options
  • Save lnmunhoz/ee3315d4cff7de61cd4417250f262174 to your computer and use it in GitHub Desktop.
Save lnmunhoz/ee3315d4cff7de61cd4417250f262174 to your computer and use it in GitHub Desktop.
learning d3: axis
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 margin = {
left: 100,
right: 10,
top: 10,
bottom: 100
}
const width = 600 - margin.left - margin.right
const height = 400 - margin.top - margin.bottom
const svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", width + margin.top + margin.bottom)
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`)
const x = d3.scaleBand()
.domain(buildingsData.map(d => d.name))
.range([0, 400])
.paddingInner(0.3)
.paddingOuter(0.3)
const y = d3.scaleLinear()
.domain([0, d3.max(buildingsData, d => d.height)])
.range([0, height])
const xAxisCall = d3.axisBottom(x)
const yAxisCall = d3.axisLeft(y)
g.append("g")
.attr("transform", `translate(0, ${height})`)
.call(xAxisCall)
.selectAll("text")
.attr("text-anchor", `end`)
.attr("x", -5)
.attr("y", 10)
.attr("transform", `rotate(-40)`)
g.append("g")
.call(yAxisCall)
const rects = g.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