【问题标题】:Looking for a way to display labels on sunburst chart (could not find a working example)寻找一种在旭日形图上显示标签的方法(找不到工作示例)
【发布时间】:2012-10-30 07:57:11
【问题描述】:

感谢某人的帮助 (Brandon),我能够在旭日形图中添加工具提示。 我仍在寻找一种在旭日图上显示路径标签的方法(然后有双模式工具提示+文本)。

jsfiddle.net/trakkasure/UPqX5/上提供了我想改进的示例

我正在寻找要添加到以下代码部分的代码:

path = svg.data([getData()]).selectAll("path") 
    .data(partition.nodes)
    .enter().append("svg:path")  
    .attr("d", arc)  
    .style("fill", function(d) { return color((d.children ? d : d.parent).name); })  
    .on("click", magnify)  
    .on("mouseover", function(d) {  
    tooltip.show([d3.event.clientX,d3.event.clientY],'<div>'+d.name+'</div>  <div>'+d.value+'</div>')
    })  
    .on('mouseout',function(){  
    tooltip.cleanup()
    })              
    .each(stash);

我想查看http://bl.ocks.org/910126 上提供的示例中的标签。我无法让该示例为我工作(我还是 D3 的新手)

我确实认识到该图表上可能有太多文本,但在我的情况下这不是问题。

谁能帮我理解如何在图表上显示所有这些标签?

【问题讨论】:

    标签: javascript d3.js label hierarchy sunburst-diagram


    【解决方案1】:

    只需将 svg:text 元素附加到画布:

    path.append("svg:text")
      .attr("transform", function(d) { return "rotate(" + (d.x + d.dx / 2 - Math.PI / 2) / Math.PI * 180 + ")"; })
      .attr("x", function(d) { return d.y; })
      .attr("dx", "6") // margin
      .attr("dy", ".35em") // vertical-align
      .text(function(d) { return d.name; });
    

    但是,在我的编辑中,这会破坏您的 magnify 功能,因此我创建了一个 svg 组来将每对路径和文本保存在一起。在我看来,元素以这种方式组织得更好,将来更容易查询。

    请注意,您需要修改您的 magnify 函数以同时为文本设置动画,因为现在它只为路径设置动画并将文本保留在其原始位置。

    group = svg.data([getData()]).selectAll("path")
      .data(partition.nodes)
      .enter().append('svg:g');
    
    //path variable is required by magnify function
    path = group.append("svg:path")
      .attr("d", arc)
      .style("fill", function(d) { return color((d.children ? d : d.parent).name); })
      .on("click", magnify)
      .on("mouseover", function(d) {
        tooltip.show([d3.event.clientX,d3.event.clientY],'<div>'+d.name+'</div><div>'+d.value+'</div>')
      })
      .on('mouseout',function(){
        tooltip.cleanup()
      }) 
      .each(stash);
    
    // you may need to assign the result to a variable, 
    // for example to animate the text in your magnify function, 
    // as shown in the path variable above
    group.append("svg:text")
      .attr("transform", function(d) { return "rotate(" + (d.x + d.dx / 2 - Math.PI / 2) / Math.PI * 180 + ")"; })
      .attr("x", function(d) { return d.y; })
      .attr("dx", "6") // margin
      .attr("dy", ".35em") // vertical-align
      .text(function(d) { return d.name; });
    

    代码取自您给定的example,但是 我将x 属性编辑为.attr("x", function(d) { return d.y; }),以根据您的数据结构正确定位文本(示例使用Math.sqrt(d.y))。我还修改了text函数返回d.name

    这里是jsFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 2019-07-04
      • 2022-01-20
      相关资源
      最近更新 更多