Thursday, 15 April 2021

Multiple draggable charts d3.js

I need to display multiple draggable donut charts using d3.js using JSON data. I can display multiple charts by calling the function twice but only the first chart will drag. Alternatively I have tried using a 2D array which displays multiple charts but none will drag. Help appreciated. code is:

function showChart() {

    $.getJSON('data.json', function (data) {

    var newData = [];
    for (var key in data.items[0]) {
        var thisData = {
                "Name": key,
                "Value": data.items[0][key]
        }
        newData.push(thisData)  
    }

    var width = 160;
    var height = 160;
    var outradius = Math.min(width, height) / 2;
    var inradius = outradius / 1.25;
    var boxWidth = 600;  
    var boxHeight = 400;
    var color = d3.scale.category10();

    var svg = d3.select('#Chart')
        .append('svg')
        .attr('class', 'svg')
        .attr('width', 400)
        .attr('height', 400);

    var arc = d3.svg.arc()
        .outerRadius(outradius)
        .innerRadius(inradius);

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

    var path = svg.selectAll('path')
        .data(pie(newData))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
                return color(d.data.Name);
        })

        .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended))

        .attr('transform', 'translate(' + (width / 2) + ',' +   (height / 2) + ')');

    var path2 = d3.select('svg').data(pie(newData))
        .enter().append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
            return color(d.data.Name);
        })

        .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended))
        .attr('transform', 'translate(' + (width / 2) + ',' +   (height / 2) +     ')');
    function dragstarted(d) {
        //... 
    }
    function dragged(d) {   
        var x = d3.event.x;
        var y = d3.event.y;
        d3.select('svg')
            .attr('transform', 'translate(' + x + ',' +     y + ')');
    }

    function dragended(d) {
        //...
    }   

    });
}

Thank you.



from Multiple draggable charts d3.js

No comments:

Post a Comment