D3:删除元素

时间:2013-04-28 06:33:06

标签: javascript d3.js

我有一个创建正负条形图的条形图。我试图稍后删除负条,但是现在,即使在附加条形图后,如果我尝试立即移除负条,它们仍会出现。

var margin = {top: 30, right: 10, bottom: 10, left: 10},
    width = 750 - margin.left - margin.right,
    height = data.length * 20 //500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width*.85])

//chart1.x =x
//chart1.y = y

var y = d3.scale.ordinal()
    .rangeRoundBands([0, height], 0);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("top");

var svg = d3.select("#barchart").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 + ")");

//d3.tsv("data.tsv", type, function(error, data) {
  x.domain(d3.extent(data, function(d) { return +d.netdonations_over_population_to_gdppercap_percentage; })).nice();
  y.domain(data.map(function(d) { return d.name; }));

  bar = svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", function(d) { return +d.netdonations_over_population_to_gdppercap_percentage < 0 ? "bar negative" : "bar positive"; })
      .attr("x", function(d) { return x(Math.min(0, +d.netdonations_over_population_to_gdppercap_percentage)); })
      .attr("y", function(d) { return y(d.name); })
      .attr("width", function(d) { return Math.abs(x(+d.netdonations_over_population_to_gdppercap_percentage) - x(0)); })
      .attr("height", y.rangeBand()).style("stroke","white")

bar.selectAll(".negative").data([]).exit().remove()

remove语句是最后一个。其余的代码:

svg.selectAll("text")
    .data(data)
  .enter().append("text").text(function(d) {
        return d;
   }).attr("y", function(d, i) {
        return y(d.name)+ y.rangeBand();
        //return i * (height / data.length)+30;
   }).attr("x", function(d) {
         return x(0) //x(Math.min(0, +d.netdonations_over_population_to_gdppercap_percentage));
   }).text(function(d) {
        //return y(d) + y.rangeBand() / 2;
        return d.name + " " + d.netdonations_over_population_to_gdppercap_percentage;
        }).style("font-size","14px").attr("dx", 3).attr("dy", "-0.45em")


  svg.append("g")
      .attr("class", "x axis")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
    .append("line")
      .attr("x1", x(0))
      .attr("x2", x(0))
      .attr("y2", height);

1 个答案:

答案 0 :(得分:92)

尝试将您的selectAll语句切换为:

svg.selectAll("rect.negative").remove()

这应该选择带有rect类的代码negative,但我不是100%确定它会找到它,因为attr class被写为{{1} }}。如果它不起作用,我可能会尝试将您的bar negative属性更改为class或仅negative bar

很抱歉,如果这没有帮助!