D3将两个圆环图添加到彼此之上。

时间:2015-02-20 20:26:19

标签: javascript jquery d3.js

我希望以某种方式将两个甜甜圈图表叠加在一起,或者至少只是弧线。我想隐藏一个特定的弧,并在单击时显示另一个,然后再次单击还原。

我想通过选择该切片并执行d3.select("the arc").attr("visibility", "hidden");

,您可以在点击时隐藏弧线

所以我想隐藏一个切片,然后显示另一个切片。我希望弧线占据相同的位置,因此显示另一个看起来只会改变弧线。

谢谢你, 布赖恩

1 个答案:

答案 0 :(得分:0)

据我了解您的问题,您希望在点击时更新特定的弧。 因此,不是创建两个甜甜圈,而是创建一个甜甜圈,只需创建一个圆环图并在点击圆弧时更新它。



 $(document).ready(function() {

   var width = 400,
     height = 250,
     radius = Math.min(width, height) / 2;

   var color = d3.scale.category20();

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

   var arc = d3.svg.arc()
     .innerRadius(radius - 70)
     .outerRadius(radius - 20);

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

   var data = [{
     "apples": 53245,
     "oranges": 200
   }, {
     "apples": 28479,
     "oranges": 200
   }, {
     "apples": 19697,
     "oranges": 200
   }, {
     "apples": 24037,
     "oranges": 200
   }];

   var path = svg.datum(data).selectAll("path")
     .data(pie)
     .enter().append("path")
     .attr("fill", function(d, i) {
       return color(i);
     })
     .attr("d", arc)
     .each(function(d) {
       this._current = d;
     }) // store the initial angles
     .on("click", function(d) {
       var key = d.data.getKeyByValue(d.value);
       var oppKey = (key === "apples") ? "oranges" : "apples";
       change(oppKey);
     });

   function change(keyVal) {
     var value = keyVal;
     pie.value(function(d) {
       return d[value];
     }); // change the value function
     path = path.data(pie); // compute the new angles
     path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
   }

   function type(d) {
     d.apples = +d.apples;
     d.oranges = +d.oranges;
     return d;
   }

   // Store the displayed angles in _current.
   // Then, interpolate from _current to the new angles.
   // During the transition, _current is updated in-place by d3.interpolate.
   function arcTween(a) {
     var i = d3.interpolate(this._current, a);
     this._current = i(0);
     return function(t) {
       return arc(i(t));
     };
   }

   Object.prototype.getKeyByValue = function(value) {
     for (var prop in this) {
       if (this.hasOwnProperty(prop)) {
         if (this[prop] === value)
           return prop;
       }
     }
   }
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;

相关问题