javascript - 如何将图例定位到圆环图的右侧

标签 javascript d3.js svg

这是我的 plunkr code , 在图例居中的这个位置,我如何将它定位到圆环图的右侧?

var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2 - radius) +
        ',' + (height / 2 - radius) + ')');

我试过上面的代码,但它不起作用。

最佳答案

定义新变量并以像素为单位设置图例宽度:

var legendWidth = 150;

将此变量用于 svg 元素宽度:

var svg = d3.select('#chart')
  .append('svg')
  .attr('width', width + legendWidth) // <== !!!
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(' + (width / 2) +
    ',' + (height / 2) + ')');

以这种方式重写图例 transform 属性的函数:

var legend = svg.selectAll('.legend')
  .data(color.domain())
  .enter()
  .append('g')
  .attr('class', 'legend')
  .attr('transform', function(d, i) {
    var height = legendRectSize + legendSpacing;
    var offset =  height * color.domain().length / 2;
    var vert = i * height - offset;
    return 'translate(' + width / 2 + ',' + vert + ')'; // <== move every legend item on half of width
  });

检查 working example here .

关于javascript - 如何将图例定位到圆环图的右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47669613/

相关文章:

javascript - 无法读取 jquery 中未定义的属性 '0'

javascript/jquery 泄漏和浏览器崩溃

javascript - 使用困惑的查询(HTML 表)从 JSON url 添加数据

javascript - 解析 JavaScript 上传或更新文件匹配表中行的 objectId

javascript - 如何在使用 d3 拖动时禁用 mouseover 和 mouseout 事件?

javascript - 在 D3.js 图中格式化标签

python - 使用 BeautifulSoup 从多个 svg 帧创建循环 svg 动画

html - 如何使用:before to add <use> for <svg> tags?

events - d3.js - 转换中断事件?

svg - 使用固定大小的元素来增长 svg?