Skip to content

Instantly share code, notes, and snippets.

@foxbunny
Created March 31, 2018 11:58
Show Gist options
  • Save foxbunny/753c18573db05e0c918f5f3a4a7b4635 to your computer and use it in GitHub Desktop.
Save foxbunny/753c18573db05e0c918f5f3a4a7b4635 to your computer and use it in GitHub Desktop.
Basic bar chart
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>
<svg height="100%" width="100%">
</svg>
<script>
const rectWidth = 10
const height = 274
const domainData = [100, 200, 175, 200, 120]
const domainExtent = d3.max(domainData)
const colors = d3.scaleQuantize()
.domain([100, domainExtent])
.range([
'#f3f3f3',
'#efefef',
'#ddd',
'#939393',
'#7a7a7a',
'#000',
])
const yCoordScale = d3.scaleLinear()
.domain([0, domainExtent])
.range([0, height])
const reverseYCoordScale = d3.scaleLinear()
.domain([0, domainExtent])
.range([height, 0])
const svg = d3.selectAll('svg')
.style('padding', '30px')
const leftAxis = d3.axisLeft()
.scale(reverseYCoordScale)
.ticks(3)
svg
.append('g')
.attr('transform', 'translate(30, 0)')
.call(leftAxis)
const rects = svg
.append('g')
.attr('transform', 'translate(40, 0)')
.selectAll('rect')
.data(domainData)
.enter()
.append('rect')
.attr('x', (d, i) => i * rectWidth)
.attr('y', reverseYCoordScale)
.attr('width', rectWidth)
.attr('height', yCoordScale)
.attr('fill', colors)
.attr('stroke', 'white')
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment