How to update the d3js – graph data alone without re-appending `svg` element

How to update the data of the existing graph in d3.js. i am trying but i am getting error.

Actually, this is my requirement for angular. i have a single directive withing that, i would like to update data by sending different scenario of function call.

here is my try :

$(function(){

  var data = [30, 70];
  var phrase = "Graphics";
  var datas = [
      [40,60],
      [85,15],
      [20,80]
    ]

  var drawPie = function (array, phrase, element) {



                var width = element.width(), height = element.height(),
                radius = Math.min(width, height) / 2, data = array;


                if(!data.length) return;

                var color = d3.scale.ordinal()
                    .domain(data)
                    .range(["#ffff00", "#1ebfc5"]);

                var arc = d3.svg.arc()
                    .outerRadius(radius - 10)
                    .innerRadius(radius - 5);

                var pie = d3.layout.pie()
                    .sort(null)
                    .value(function(d) { return d });

                var svg = d3.select(element[0]).append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .append("g")
                    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");


                 var g = svg.selectAll(".arc")
                      .data(pie(data))
                        .enter().append("g")
                        .attr("class", "arc");

                  g.append("path")
                      .attr("d", arc)
                      .style("fill", function(d,i) { return color(d.data); });

                 g.append("text")
                     .text(data[0]+'%')
                     .attr("transform", "translate(" + 0 + "," + radius / 4 + ")")
                     .attr("class", "designVal")
                     .style("text-anchor", "middle")


            }

    drawPie( data, phrase, $('#first'));    
    drawPie( data, phrase, $('#second'));

    $('button').on('click', function() {
      var index = $(this).index();
      var array = datas[index]; //getting different array;
      d3.select('#second').selectAll("path").data(pie(array)) //not setting
    })

});

Live Demo


Source: jquery

Leave a Reply