Day 98 of 100 Days Of Code
Day 98: October 30, Tuesday
Today ‘s Progress Still on my break from TDD and did a couple D3.js challenges on FreeCodeCamp Data Visualization with D3: Dynamically Set the Coordinates for Each Bar.
Thoughts Had to take a break from TDD its making my head hurt…
Resources used:
- D3: setting style conditionally with immediately invoked arrow function and ternary
- D3 Tutorial
- D3 in Depth
Dynamically Set the Coordinates for Each Bar
Example: The attr()
method in D3 accepts a callback function to dynamically set that attribute. The callback function takes two arguments, one for the data point itself (usually d) and one for the index of the data point in the array. The second argument for the index is optional. Here’s the format:
selection.attr("property", (d, i) => {
/*
* d is the data point value
* i is the index of the data point in the array
*/
})
It’s important to note that you do NOT need to write a for loop or use forEach()
to iterate over the items in the data set. Recall that the data()
method parses the data set, and any method that’s chained after data()
is run once for each item in the data set.
Challange Instructions: Change the x
attribute callback function so it returns the index times 30.
Note Each bar has a width of 25, so increasing each x value by 30 adds some space between the bars. Any value greater than 25 would work in this example.
My solution
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
const w = 500;
const h = 100;
const svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", (d, i) => {
// Add your code below this line
return i*30;
// Add your code above this line
})
.attr("y", 0)
.attr("width", 25)
.attr("height", 100);
</script>
</body>
Link(s) to work
- Working on learning VUE-TDD application.
- PassedCreate a Bar for Each Data Point in the Set
- PassedDynamically Set the Coordinates for Each Bar
Code is at Data Visualization with D3.