简体   繁体   English

position 如何在 d3.js 中获得圆环图的图例权利?

[英]How to position the legend right to donut chart in d3.js?

I am facing the issue to shift the legend outside ie right to donut chart.I have tried lot of option to shift the legend to right of donut but unable to get right approach.I am using the d3.js library.我正面临将图例移到甜甜圈图右侧的问题。我尝试了很多选项将图例移到甜甜圈的右侧,但无法获得正确的方法。我正在使用 d3.js 库。 please see the image in which I am getting legend in centre of donut chart.请查看我在圆环图中心获得图例的图像。 enter image description here在此处输入图像描述

d3.js script:- d3.js 脚本:-

var dataset = [
    { name: 'Data', percent: 100 },
    { name: 'Chrome', percent: 32.51 },
    { name: 'Safari', percent: 23.68 },
    { name: 'Opera', percent: 50.71 },
    { name: 'Firefox', percent: 8.71 },
    { name: 'Others', percent: 36.01 }
];
 
var pie=d3.layout.pie()
  .value(function(d){return d.percent})
  .sort(null)
  .padAngle(.03);
 
var w=500,h=500;
 
var outerRadius=w/2;
var innerRadius=w/3;
 
var color = d3.scale.category10();
 
var arc=d3.svg.arc()
  .outerRadius(outerRadius)
  .innerRadius(innerRadius);
 
var svg=d3.select("#chart")
  .append("svg")
  .attr({
      width:w,
      height:h,
      class:'shadow'
  })
  //.style("filter", "url(#drop-shadow)")
  .append('g')
  .attr({
      transform:'translate('+w/2+','+h/2+')'
  });

// filters go in defs element
var defs = svg.append("defs");

// create filter with id #drop-shadow
// height=130% so that the shadow is not clipped
var filter = defs.append("filter")
    .attr("id", "drop-shadow")
    .attr("height", "130%");

// SourceAlpha refers to opacity of graphic that this filter will be applied to
// convolve that with a Gaussian with standard deviation 3 and store result
// in blur
filter.append("feGaussianBlur")
    .attr("in", "SourceAlpha")
    .attr("stdDeviation", 15)
    .attr("result", "blur");

// translate output of Gaussian blur to the right and downwards with 2px
// store result in offsetBlur
filter.append("feOffset")
    .attr("in", "blur")
    .attr("dx",100)
    .attr("dy", 100)
    .attr("result", "offsetBlur");

// overlay original SourceGraphic over translated blurred opacity by using
// feMerge filter. Order of specifying inputs is important!
var feMerge = filter.append("feMerge");

feMerge.append("feMergeNode")
    .attr("in", "offsetBlur")
feMerge.append("feMergeNode")
    .attr("in", "SourceGraphic");


var path=svg.selectAll('path')
  .data(pie(dataset))
  .enter()
  .append('path')
  .attr({
      d:arc,
      fill:function(d,i){
          return color(d.data.name);
      }
  });
 
path.transition()
  .duration(1000)
  .attrTween('d', function(d) {
      var interpolate = d3.interpolate({startAngle: 0, endAngle: 0}, d);
      return function(t) {
          return arc(interpolate(t));
      };
  });
 
 
var restOfTheData=function(){
    var text=svg.selectAll('text')
        .data(pie(dataset))
        .enter()
        .append("text")
        .transition()
        .duration(500)
        .attr("transform", function (d) {
            return "translate(" + arc.centroid(d) + ")";
        })
        .attr("dy", ".4em")
        .attr("text-anchor", "middle")
        .text(function(d){
            return d.data.percent+"%";
        })
        .style({
            fill:'#fff',
            'font-size':'10px'
        });
 
    var legendRectSize=20;
    var legendSpacing=7;
    var legendHeight=legendRectSize+legendSpacing;
 
 
    var legend=svg.selectAll('.legend')
        .data(color.domain())
        .enter()
        .append('g')
        .attr({
            class:'legend',
            transform:function(d,i){
                //Just a calculation for x & y position
                return 'translate(-35,' + ((i*legendHeight)-65) + ')';
            }
        });
    legend.append('rect')
        .attr({
            width:legendRectSize,
            height:legendRectSize,
            rx:20,
            ry:20
        })
        .style({
            fill:color,
            stroke:color
        });
 
    legend.append('text')
        .attr({
            x:30,
            y:15
        })
        .text(function(d){
            return d;
        }).style({
            fill:'#929DAF',
            'font-size':'14px'
        });
};
 
setTimeout(restOfTheData,2000);

Right now you are positioning the individual parts of your legend based on the size of the.现在,您正在根据图例的大小定位图例的各个部分。 You can simplify this by creating a that contains all of your legend elements and translating that to its desired position in the graph.您可以通过创建一个包含所有图例元素并将其转换为图中所需的 position 来简化此操作。

You'll need to play around with the values to get exactly what you want, but below are the values that would allow you to place the legend in the right margin.您需要使用这些值来获得您想要的结果,但以下是允许您将图例放置在右边距中的值。

var margin = {top: 20, right: 100, bottom: 30, left: 40};

var legendHolder = svg.append('g')
  // translate the holder to the right side of the graph
  .attr('transform', "translate(" + (margin.left + width) + ",0)")

var legend = legendHolder.selectAll(".legend")
    .data(ageNames.slice().reverse())
  .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

legend.append("rect")
  .attr("x", 0)
  .attr("width", 18)
  .attr("height", 18)
  .style("fill", color);

legend.append("text")
  .attr("x", 0)
  .attr("y", 9)
  .attr("dy", ".35em")
  .style("text-anchor", "end")
  .text(function(d) { return d; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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