I am very new with javascript and I am hoping to receive any guidance I can here - I am currently trying to create a dashboard that will dash data from a csv with 2 filters. One drop down - which is the region, and one slider which is the year.
The data looks something like this:
Country,Metric1,Metric2,Region,Year
I set up the graph by the usual svg select data enter append method, but I am currently trying to add smooth transition when a different year was selected (slider moved) with the same region. I have no problem redrawing the graph -
(What I tried without transition)
function update_data(year,region) {
//remove old graph
d3.select("svg").remove();
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//Read the data
d3.csv("data.csv", function(data) {
// Add X axis
var x = d3.scaleLinear()
.domain([1000, 55000])
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5));
// Add Y axis
var y = d3.scaleLinear()
.domain([0, 300])
.range([ height, 0]);
var color = d3.scaleOrdinal()
.domain(['Asia', 'Europe', 'Africa', 'Americas', 'Oceania'])
.range(['#a8e6cf','#dcedc1', '#ffd3b6', '#ffaaa5','#ff8b94']);
svg.append("g")
.call(d3.axisLeft(y).ticks(5));
//add new data each dot is a country
svg.append('g')
.selectAll("dot")
.data(data)
.enter()
.append("circle")
.filter(function(d) {
return +d.year == year && d.region == region;
})
.attr("cx", function (d) {
return x(d.Metric1); } )
.attr("cy", function (d) { return y(Metric2); } )
.attr("r", 4)
.style("fill", function (d) { return color(d.region); });
});
}
What I am trying is to allow smooth transition between the data points, just different year. This is what I tried - I have attached this function to a slider - however when I moved the slider nothing seems to be happening. I thought that since the amount of data points are the same, I just simply need to change the x and y attributes
function update_year(year,region) {
//Read the data
d3.csv("data.csv", function(data) {
svg.selectAll("circle")
.data(data)
.filter(function(d) {
return +d.year == year && d.region == region;
})
.transition()
.duration(1000)
.attr("cx", function (d) {
return x(d.Metric1); } )
.attr("cy", function (d) { return y(Metric2); } )
.attr("r", 4)
.style("fill", function (d) { return color(d.region); });
});
}
Any guidance is greatly appreciated on what I can do. Thank you so much in advance!