NewBie for d3.js. I try to remove xAxis, based on the method
s.selectAll("g").remove(xAxis);
but it does not work. Not sure if it is the correct way to remove xAxis? Thank you in advance.
1. var xAxis = d3.axisBottom()
.scale(xScale);
2. s.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
3. s.selectAll("g").remove(xAxis);
.remove() doesn't take any arguments, it is just a method you can use on any d3 selection.
To remove features you have to first select them, and then remove them:
d3.selectAll('g').remove(); // removes all 'g' elements from the DOM.
d3.selectAll('.point').remove(); // removes all elements with the class 'point'
To illustrate, the following code draws a circle:
var svg = d3.select('body').append('svg');
var circle = svg.append('circle')
.attr('cx',40)
.attr('cy',40)
.attr('r',10);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
You can remove the circle multiple ways. You could use circle.remove(); as the variable circle is a selection that includes that circle.
Or you could select circles that are in the svg: svg.selectAll('circle').remove();
Or you could just select all circles in the DOM with d3.selectAll('circle').remove();
Method 1:
var svg = d3.select('body').append('svg');
var circle = svg.append('circle')
.attr('cx',40)
.attr('cy',40)
.attr('r',10);
circle.remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Method 2:
var svg = d3.select('body').append('svg');
var circle = svg.append('circle')
.attr('cx',40)
.attr('cy',40)
.attr('r',10);
svg.selectAll('circle').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Method 3:
var svg = d3.select('body').append('svg');
var circle = svg.append('circle')
.attr('cx',40)
.attr('cy',40)
.attr('r',10);
d3.selectAll('circle').remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
In your case you could try variations of the above approaches:
var axis = s.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
axis.remove();
Or you could give it a class or id and use that to remove it:
s.append("g")
.attr("class", "x axis")
.attr('id', 'xAxis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
d3.selectAll('#xAxis').remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With