BTS D3.js Lesson #4 — Statistics Chart Setup
Set up structure to plot data on all 7 BTS band members
Previous Lessons
Learning Resources
index.html
Add in the new code below the form in the top portion of the application.
Create the HTML code for the structure below.
- create the
<svg>
element inside of the HTML, below the<h1>
tag. assign an id ofchart
to the<svg>
element - input type is “radio”
- name = “stats”
- value=”weight” or “height”
- class=”statsButton”
<hr>
<hr>
<h1 id="statsTitle"> Member Information</h1>
<svg id='chart'></svg>
<form>
<input type="radio" name="stats" value="height" class="statsButton">
<label>Height</label>
<input type="radio" name="stats" value="weight" class="statsButton">
<label>Weight</label>
</form>
In the inspector, note that you have two SVG viewports and two forms.
drawChart.js
create a constant called chartSettings
. Assign it to an object (curly brackets). Parameters and values are below. Note that margin
is an object inside of an object.
const chartSettings = {
width: 600,
height: 300,
imageSize: 60,
idHtml: '#chart', margin: {left: 100, right: 50, top: 50, bottom: 50}};
- Read in data file
- Print out data to console
d3.csv(…).then(variable name){ …code..}
// read in data from file
d3.csv('data/bts-profiles.csv').then(data => {
console.log(data);
});
chartClass.js
create a class called, BtsChart
.
create a method called, changeStats)
Test chartClass.js from drawChart.js
- create a new object
chart
from the classBtsChart
- print out
chart.width
- print out
chart.height
d3.csv('data/bts-profiles.csv').then(data => {
const chart = new BtsChart(chartSettings, data);// tests
console.log(chart.width);
console.log(chart.margin);});
Grab button change information
create a constant buttons
to hold the selectAll
results from selecting the HTML buttons of class .statsButtons
const statsButtons = d3.selectAll(".statsButton");
- on change of statsButtons, run an anonymous function
- in the anonymous function, assign a constant
statsSelection
tothis.value
- run
chart.changeStats(…)
// read in data from file
d3.csv('data/bts-profiles.csv').then(data => {
const chart = new BtsChart(chartSettings, data);const statsButtons = d3.selectAll(".statsButton");
statsButtons.on('change', function(d) {
const statsSelection = this.value;
chart.changeStats(statsSelection);
});
});
modify changeStats in chartClass.js
go back to chartClass.js
modify the console.log
to print out the selection. See the example below.
changeStats(selection) {
console.log(`changing stats to ${selection}`);
}
}
Congratulations
You’ve finished lesson #4 and are on your way to mastering charting with D3.js.