简体   繁体   中英

How to update a D3 chart dynamically

I am trying to create an easy way to create and update donut charts (And other charts, later) in an application. This is built on top of D3.

I've created a drawDonutChart as shown below:

var data =  [50, 50];
var dataTwo = [75, 25];
var options = {
  colors: ["#0074D9", "#7FDBFF"],  
};

function createDonutChart(data, height, width, domElement, options) {

    var radius = Math.min(width, height);
    var color = d3.scale.category20();
    var donut = d3.layout.pie().sort(null);

    var arc = d3.svg.arc()
        .innerRadius(radius/4)
        .outerRadius(radius/2);

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

    var path = svg.selectAll("path")
        .data(donut(data))
        .enter().append("path")
        .attr("fill", function(d, i) {
            if (options.colors == null || options.colors == "undefined") {
                return color(i);
            } else {
                return options.colors[i];
            }
        }).attr("d", arc);

}

var donutChart = createDonutChart(data, 50, 50, ".slices", options);

when you have a in the page, this will draw a donut chart there.

I would like to write a function updateDonutChart(originalChart, newData), pass it (donutChart, dataTwo) and have it transition this data into the chart instead of the old data.

I've been looking at multiple examples on the D3 website but I haven't been able to get something to work this way (where you simply pass the old chart, and new data). It might be simple, I am just new to D3 :)

Thanks in advance for the help.

So, it wasn't clear to me from the signature of your update call if you wanted to create a new SVG under a possibly new DOM element every time you updated the chart. Also, I am not sure if you are using the word transition to specify a D3 transition of just a change in the data (although that would be simple enough to add). I any case, a simple adaptation to your code to do what you want is in this FIDDLE .

function updateDonutChart(data, options) {...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM