Charts can change based on audience interaction. For example, if your audience presses on a button, the chart could change completely.
When the chart changes, the number of data elements can change.
You need to delete the old data from chart.
https://bl.ocks.org/codetricity/ed19971e73117daa771ff1bd7de8e519
selectAll(element)
selects an element such as circle or li (for list item).data(dataset)
binds the data to an element.enter()
returns the invisible elements that are bound to data.exit()
returns the visible elements that are not bound to data
- Create a new project
- add
index.html
,main.js
, andd3.js
.
const animals = ['dog', 'cat', 'tiger', 'lion'];
const orderedList = d3.select('body').append('ol');
orderedList.selectAll('li')
.data(animals)
.enter()
.append('li')
.text(d => d);
const trees = ['oak', 'maple', 'apple', 'pine'];
orderedList.selectAll('li')
.data(trees)
.text(d => d);
const flowers = ['rose', 'tulip'];
orderedList.selectAll('li')
.data(flowers)
.text(d => d)
Extra items from the previous dataset.
orderedList.selectAll('li')
.data(flowers)
.text(d => d)
.exit()
.remove();
In the HTML file add a form of radio buttons
<body>
<form>
<label>
<input type='radio' value='trees' name='garden' />
trees
</label>
<label>
<input type='radio' value='animals' name='garden' />
animals
</label>
<label>
<input type='radio' value='flowers' name='garden' />
flowers
</label>
</form>
let buttons = d3.selectAll('input');
function getButton() {
console.log(this.value);
}
buttons.on('change', getButton);
function getButton() {
let dataset;
if (this.value == 'flowers') {
dataset = flowers;
} else if (this.value == 'trees') {
dataset = trees;
} else if (this.value == 'animals') {
dataset = animals;
}
orderedList.selectAll('li').remove();
orderedList.selectAll('li')
.data(dataset)
.enter()
.append('li')
.text(d => d);
console.log(this.value);
}
---