Skip to content

Instantly share code, notes, and snippets.

@molliemarie
Created January 27, 2020 19:57
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/0fe151e7f3d0cd82d88945c87f348e6f to your computer and use it in GitHub Desktop.
Save molliemarie/0fe151e7f3d0cd82d88945c87f348e6f to your computer and use it in GitHub Desktop.
Scatter3_D3WithDataJoin_ClassWork
license: mit
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Second Scatter Using D3 AND Data Joins!</title>
<style>
/* Set `circle` elements to have a "fill" of "purple" or whatever color you choose */
circle {
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.
const 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 D3 Data Join Scatter"
div.append('p').text('My D3 Data Join Scatter')
// - Append a container `svg` to your `div` element in which you'll place your circles
// - Set your svg's `width` to 300, and `height` to `400`
const svg = div.append('svg')
.attr('width', 300)
.attr('height', 400)
// 1) Append 3 `circle` elements inside of your `<svg>` (one at a time), setting the properties for each one. We'll improve on this process later:
// - `cx`: How far to move the circle in the `x` direction (right). Should be 100, 150, and 200.
// - `cy`: How for to move the circle in the `y` direction (down from the top). Should be 100, 150, and 200.
// - 'r': circle's radius. Should be 10, 15, and 20.
// This is the dataset to drive the layout:
const data = [{
cx: 100,
cy: 100,
r: 10
},
{
cx: 150,
cy: 150,
r: 15
},
{
cx: 200,
cy: 200,
r: 20
},
];
// Select all circles in the svg and bind your data to the selection
svg.selectAll('circle')
.data(data)
.enter().append('circle')
.attr('cx', function(d) { return d.cx })
.attr('cy', function(d) { return d.cy})
.attr('r', function(d) { return d.r})
// Determine what's new to the screen using `.enter()` and for each new element, append a circle
// Then, use the data provided to set the desired attributes
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment