Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to start a D3JS pie chart with all values being 0?

I'm making a simple tool to display a set of values that are manipulated by the user. I want all the values to start at 0 and when the data is manipulated, to grow from there.

I have everything setup except that I get errors in the console when I start all my values at 0.

Is this possible?

Here's the code I have at the moment (which is working if the values are greater than 0):

    var width = this.get('width');
    var height = this.get('height');
    var radius = Math.min(width, height) / 2;
    var color = this.get('chartColors');
    var data = this.get('chartData');

    var arc = d3.svg.arc()
        .outerRadius(radius)
        .innerRadius(0);


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


    var id = this.$().attr('id');
    var svg = d3.select("#"+id)
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var g = svg.selectAll("path")
        .data(pie(data));

    g.enter()
        .append("path")
        .attr("d", arc)
        .each(function(d){ this._current = d; })
        .style("fill", function(d, i) { return color[i]; })
        .style("stroke", "white")
        .style("stroke-width", 2);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is a conceptual one -- if everything is 0, how are you going to draw a pie chart? You could however start with an empty data set and add new data as it becomes greater than zero. That leaves the problem of animating the growth of a pie chart segment from 0 to its desired size.

For this, you can animate the end angle of the pie chart segments starting at the start angle. The easiest way to do this is to copy the corresponding data object and tween the angle:

.each(function(d) {
    this._current = JSON.parse(JSON.stringify(d));
    this._current.endAngle = this._current.startAngle;
})
.transition().duration(dur).attrTween("d", arcTween);

Random example here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...