Skip to content

Instantly share code, notes, and snippets.

@molliemarie
Last active February 3, 2020 02:18
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/114bc4179a51fa8999a0becc8ce2acd2 to your computer and use it in GitHub Desktop.
Save molliemarie/114bc4179a51fa8999a0becc8ce2acd2 to your computer and use it in GitHub Desktop.
BarChart2_D3_Complete
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Second Bar Chart Using D3!</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">
// 1) 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')
// 2) Append a new `p` element to the `div` you just created, and use the `.text()` method to set the text to "My Bar Chart"
// How this would look if you defined each separately:
// p_tag = div.append('p')
// text = p_tag.text('My Bar Chart')
// Saming thing using chaining:
div.append('p').text('My Bar Chart')
// 3) Append a container `svg` to your `div` element in which you'll place your rectangles
var svg = div.append('svg')
.attr('width', 300)
.attr('height', 400)
// 4) Append 3 `rect` elements inside of your `<svg>` (one at a time), setting the properties for each one.
var rect1 = svg.append('rect')
.attr('x', 0)
.attr('y', 10)
.attr('width', 100)
.attr('height', 20)
var rect2 = svg.append('rect')
.attr('x', 0)
.attr('y', 40)
.attr('width', 200)
.attr('height', 20)
var rect3 = svg.append('rect')
.attr('x', 0)
.attr('y', 70)
.attr('width', 300)
.attr('height', 20)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment