Reputation: 428
I currently have a dropdown and datepicker that when clicked, returns a new data source. A similar method is seen here.
This data source is used to create my graph and scale up/down the amount of data shown.
Generally, my source code follows this construct:
var updateGraphData = function(error, json) {
updateGraph(json);
}
// datepicker code goes here
// url param update code as seen in linked jsfiddle goes here
function MakeUrl() {
var urlSource = BaseURL + param1 + param2; /*these values are defined in the param code mentioned */
d3.json(urlSource, updateGraphData);
}
//set dimensions
var margin = {top: 30,right: 60,bottom: 30,left: 60
};
var width = 800 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var color = d3.scale.category10();
function updateGraph(json_data) {
/* everything I want drawn goes here, i.e. axes, lines, points, labels, etc.*/
};
Now, my appended url source code works -- the graph does re-render with the proper data set. BUT ONLY when I define my SVG element inside the updateGraph function. When I do that, a new graph renders with the proper, BUT it pops a new graph below the old one. Which is not what I want. I want my new graph to replace the old one.
When I tried pulling my SVG element before the updateGraph function (so defined where the margin and dimensions are defined), the graph didn't repeat on dropdown change, but it layered the data in such a way that I was unable to see any useful data.
Basically, I am not able to remove all my graph elements on a new data request. How would you suggest going about this? I feel like it should be as easy as using a svg.selectAll("*").remove() in my updateGraphData() function, but that just stops any data from being rendered inside the SVG at all.
Any advice for me?
Thank you very much! Let me know if I'm not being clear.
Upvotes: 0
Views: 2471
Reputation: 428
Alright Team,
After hours and hours of searching for an answer, I finally found one. Hopefully, this will help someone else.
So like I said, I was getting new graphs to append below the old graph. I was having issues getting the previous data to clear out, and I couldn't seem to figure out how to specify a specific graph to clear without clearing all of my data (old and new) away.
The solution is simply adding the line:
d3.selectAll("g > *").remove()
In my updateGraph() function.
This deletes all of the "g" elements you previously created. That way, the svg container remains and you can populate with new data.
Upvotes: 5