Skip to content

Instantly share code, notes, and snippets.

@JustinSHong
Last active April 14, 2019 18:41
Show Gist options
  • Save JustinSHong/28d24aee68a20e233e9f76c6faa9ee87 to your computer and use it in GitHub Desktop.
Save JustinSHong/28d24aee68a20e233e9f76c6faa9ee87 to your computer and use it in GitHub Desktop.
Selections
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; }
svg {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<svg>
<rect />
<rect />
<rect />
<rect />
<rect />
</svg>
<script>
const data = [100, 250, 175, 200, 120];
const rectHeight = 300;
const rectWidth = 50;
// select all rect svg elements
// bind a data el to each svg el
// assign attrs to each svg el - x, y, width, height, fill, stroke
d3.selectAll('rect')
.data(data)
.attr('x', (d, i) => {
// every bar is positioned one rectWidth from another on the x-axis
return i * rectWidth;
})
.attr('y', (d, i) => {
// every bar is positioned from the top of the container by rectHeight
return rectHeight - d;
})
.attr('width', (d, i) => {
// every bar has a width of rectWidth
return rectWidth;
})
.attr('height', (d, i) => {
// every bar has a height of rectHeight corresponding to its data val
return d;
})
.attr('fill', 'blue')
.attr('stroke', 'white')
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment