Rohit K
Rohit K

Reputation: 128

Unable to refresh svg chart on Data Change

I have a heatmap designed on d3js. I have added two filters for sorting the data. When I'm changing the filters I see the updated data in the console and the chart refreshes. But after each refresh, the earlier visualized chart still remains.

I have tried .remove() and .exit from d3. These didn't seem to work.

Here's the link for my code in codesandbox: https://codesandbox.io/s/5x6qkjw6kp

Upvotes: 4

Views: 1122

Answers (1)

Deef
Deef

Reputation: 65

Quick Answer

The way you have your code setup, you are calling the whole heatmap creation function every time a filter changes, so you're reading data, axes, everything again. Based on that, you could easily clear all elements on the chart and have them recreated from scratch, rather than using the true enter, exit, update pattern, by putting this line before you define your chart.

d3.select(".chart").selectAll("*").remove();

So your code will now look like

//Setting chart width and adjusting for margins
d3.select(".chart").selectAll("*").remove();
const chart = d3
    .select(".chart")
    .attr("width", width + margins.right + margins.left)
    .attr("height", height + margins.top + margins.bottom)
    .append("g")
    .attr(
      "transform",
      "translate(" + margins.left + "," + margins.top + ")"
    );

Enter Exit Update

This section has been heavily edited, but looking through the code, quite a lot of changes would have to be made to adapt it to make it use Enter/Exit/Update type processes. Think about putting the main creation steps at the start of the chart creation outside of the function, as these only need to run once at load (titles, axes, things like that). Clicking new elements would then not recreate the whole chart, but just alter the dataset used to create the rect objects.

This works by removing all elements which are children of the main chart group before the chart is recreated.

Hope that makes sense, let me know if anything is unclear and I'll tidy it up!

Upvotes: 3

Related Questions