I am currently utilizing D3.js to generate a bar chart based on data from a JSON file. My goal is to allow users to filter through various years and countries, but I am struggling to figure out how to select different arrays within the JSON file.
The structure of my JSON data is as follows (which may not be entirely accurate):
var NL = [
j1996 = [20317, 27395, 29273, 27170, 19441],
j1997 = [25267, 31331, 35193, 35299, 23005],
j1998 = [25576, 30643, 35484, 35796, 23343]
]
var BE = [
j1996 = [52317, 17395, 39273, 47170, 39441],
j1997 = [35267, 13331, 15193, 15299, 13005],
j1998 = [15576, 20643, 14284, 25796, 13343]
]
Furthermore, I have created buttons that trigger the loading of data for different years:
d3.select("#button1996")
.on("click", function (d, i) {
bars(j1996);
})
d3.select("#button1997")
.on("click", function (d, i) {
bars(j1997);
})
d3.select("#button1998")
.on("click", function (d, i) {
bars(j1998);
})
Here is the code for the 'bars' function:
function bars(data) {
max = d3.max(data)
var yScale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, height])
var xScale = d3.scale.ordinal()
.domain(d3.range(0, data.length))
.rangeBands([0, width], .2)
var myChart = d3.select("#chart")
var bars = myChart.selectAll("rect.bar")
.data(data)
//enter
bars.enter()
.append("svg:rect")
.attr("class", "bar")
.style('fill', '#C64567')
.attr('width', xScale.rangeBand())
.attr('x', function(d,i){ return xScale(i); })
.attr('height', 0)
.attr('y', height)
}
This approach has been successful so far:
d3.select("#button1996")
.on("click", function (d, i) {
bars(NL[0]);
})
My challenge now is to find a way to toggle between the NL and BE arrays (and possibly more in the future), while keeping track of the last selected year. Any advice on achieving this?