Skip to content

Instantly share code, notes, and snippets.

@molliemarie
Last active February 3, 2020 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save molliemarie/37f717c12f15714e824550122c6a1364 to your computer and use it in GitHub Desktop.
Save molliemarie/37f717c12f15714e824550122c6a1364 to your computer and use it in GitHub Desktop.
BarChart3_D3DataJoin_Complete
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Second Bar Chart Using D3 AND Data Joins!</title>
<style>
/* Set `rect` elements to have a "fill" of "purple" or whatever color you choose */
rect {
fill: purple;
}
svg {
border: 1px solid #f0f;
}
</style>
<!--- Load the d3 library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
// - Select your `body` and append a `div` element in which you'll render your content. To do this, you'll use the `d3.select()` method, and then the `.append()` method to append your element to your selection.
var div = d3.select('body').append('div');
// - Append a new `p` element to the `div` you just created, and use the `.text()` method to set the text to "My Bar Chart"
div.append('p').text('My Bar Chart')
// - Append a container `svg` to your `div` element in which you'll place your rectangles
// - Set your svg's `width` to 300, and `height` to `400`
var svg = div.append('svg')
.attr('width', 300)
.attr('height', 400)
// 1) Append 3 `rect` elements inside of your `<svg>` (one at a time), setting the properties for each one. We'll improve on this process later:
// - `x`: How far to move the rectangle in the `x` direction (right). Should be `0` for all rectangles.
// - `y`: How for to move the rect in the `y` direction (down from the top). Should be `10`, `40` `70`
// - `width`: How far to draw the rectangle to the right. Should be `100`,`200`, `300`
// - `height`: The vertical height of each rectangle. Should be `20` for all rectangles
// This is the dataset to drive the layout:
var data = [{
y: 10,
width: 100
},
{
y: 40,
width: 200
},
{
y: 70,
width: 300
},
];
// Select all rects in the svg and bind your data to the selection
var rects = svg.selectAll('rect')
// Determine what's new to the screen using `.enter()` and for each new element, append a rectangle
// Then, use the data provided to set the desired attributes
rects.data(data)
.enter()
.append('rect')
.attr('x', 0)
.attr('height', 20)
.attr('y', function(d,i){return d.y}) // use y attribute to drive layout
.attr('width', function(d,i){return d.width}); // use width attribute to drive layout
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment