Reputation: 23791
Here is my D3js code
function ShowGraph(data)
{
var w = 600,
h = 600,
padding = 36,
p = 31,
barwidth = 1;
var bar_height = d3.scale.linear()
.domain([d3.max(data, function(d) { return d.count; }), 0] ) // min max of count
.range([p, h-p]);
var bar_xpos = d3.scale.linear()
.domain([1580, d3.max(data, function(d) { return d.year; })] ) // min max of year
.range([p,w-p]);
var xAxis = d3.svg.axis()
.scale(bar_xpos)
.orient("bottom")
.ticks(5); //Set rough # of ticks
var yAxis = d3.svg.axis()
.scale(bar_height)
.orient("left")
.ticks(5);
var svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
svg.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("class","bar")
.attr("x", function(d) {
return bar_xpos(d.year); })
.attr("y", function(d) {
return bar_height(d.count); })
.attr("width", barwidth)
.attr("height", function(d) {return h - bar_height(d.count) - padding; })
.attr("fill", "steelblue")
}
i run the above code at the click of a button.When i click the button once the graph displays but if click it once again it shows another graph.So now i get 2 graphs.If i click once more i get 3.All i want is to update the existing graph instead of duplicating the graphs.
Upvotes: 2
Views: 4081
Reputation: 3872
You can also remove your old svg before appending the new one..
d3.select("#D3line").selectAll("svg").remove();
var svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);
Upvotes: 3
Reputation: 74036
Here you always append a new SVG element (.append('svg')
):
var svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);
So instead of using a new SVG element (and thus a new graph), just maintain a link to the first selected graph and override it or select the SVG again:
var svg = d3.select( '#D3line svg' );
if ( !svg ) {
svg = d3.select("#D3line").append("svg")
.attr("width", w)
.attr("height", h);
}
Or you clear all content of you element, where the SVG resides:
document.querySelector( '#D3line' ).innerHTML = '';
Upvotes: 4