I am doing a bar chart with Javascript D3. I want to sort the data when the checkbox is checked, and when the checkbox is unchecked, the visualization goes back to the unsorted state.
Now "sorting data when checkbox is checked" works well, but unchecking the checkbox makes no difference (which means the data still stay sorted). Any help is appreciated. Thanks in advance!
Code snippet:
<form>
<label><input type="checkbox" id="check" onchange="sortData(this);" value="sort">Sort Data</label>
</form>
<script>
var data;
function sortData(cb) {
if (cb.checked) {
// sort data
var checkedData = data;
checkedData.sort((a, b) => d3.descending(a[myCategory], b[myCategory]));
drawVis(checkedData);
} else {
// do not sort data
console.log("Unchecked!");
drawVis(data);
}
}
function drawVis(data) {
svg.selectAll(".bar").remove();
svg.selectAll("g").remove();
......
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y));
svg.selectAll(".bar")
.data(data)
.enter().append("rect");
......
}
</script>
Aucun commentaire:
Enregistrer un commentaire