BTS D3.js Lesson #4 — Statistics Chart Setup

Craig Oda
CodeCakes
Published in
3 min readNov 11, 2018

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 of chart 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

  1. create a new object chart from the class BtsChart
  2. print out chart.width
  3. 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");
  1. on change of statsButtons, run an anonymous function
  2. in the anonymous function, assign a constant statsSelection to this.value
  3. 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.

--

--

Craig Oda
CodeCakes

open source advocate, writer, Flutter developer, father, husband, fly fisherman, surfer