Bandscale practice. Scatter Plat
The lesson and code examples are here:
https://github.com/codetricity/events-practice/tree/master/scaleband
The example chart is here:
https://codetricity.github.io/events-practice/scaleband/
Bar chart
This is an exercise to reinforce the concepts from the previous lesson.
Create a blank file called bar.js Change index.html to link to bar.js instead of the previous chart.
The chart area is 600 x 400.
- create constants for width and height of chart
- create constant for margin as an object that holds left, right, top, bottom
- create constant for svgWidth and svgHeight
- create const svg to hold the viewport
- select body
- append svg
- set attributes for width and height
- chain a new group to the viewport
.append('g') - move the group to the right by margin left
- move the group down by margin top
-
use d3.csv Hint: d3.csv('filename').then(callback function)
the callback function is the code to run and is surrounded by curly brackets {}
suggest you use fat arrow function (data) => { code is here } -
test that you have read in the data by adding a console.log to callback function to print out the data
-
in the example above note that the population numbers are strings. They are enclosed in quotes. You need to convert them to integers.
data.forEach((d) => { d.population = +d.population; }); -
test that the numbers are now integers
-
add empty array called
statesthat is above the forEach loop -
inside of the
forEachloop,pushthe parameterd.stateto the end of the array -
replace the
console.logwithstates -
create a constant for
populationMinMax. Assign it tod3.extent(data, fill in here -
use console.log to test
populationMinMax. Ouput should be:Array [ 573720, 39776830 ] -
create const yScale. Use scaleLinear.
-
create const xScale. Use scaleBand. use padding of 0.1
-
create const xAxis using
d3.axisBottom -
create const yAxis
-
display xAxis by appending
gtosvg. Then, use.call(xScale)to display to screen -
display yAxis
-
bind data to
rectfor bar chart- select all rect
- bind data with
.data - enter
- append
rect
You will have a rect for each state. The rects will not appear on the screen yet.
-
add x, y, width, height attributes to rect
- x is derived from xScale with input of
d.state - width is not a fat arrow function. use
xScale.bandwidth()after the comma - height is
height - fill in- population
- x is derived from xScale with input of





