繁体   English   中英

D3 图表:我正在尝试将标签添加到在 d3 图表中创建的箭头,但它没有被添加

[英]D3 Graph: I am trying to add label to the arrow created in d3 graph but it is not getting added

我对 d3.js 相当陌生,我在 d3 图中创建了两个箭头,我试图在箭头的中心添加文本,但我看不到标签被添加到箭头中。

我的codepen链接如下:

https://codepen.io/Navin_Kris/pen/mdXwVoY

代码如下

 const data = [ { x1: 50, y1: 50, x2: 200, y2: 50, label: 'Arrow 1', rotation: '0', arrowcolor: '#62b6ae'}, { x1: 50, y1: 70, x2: 200, y2: 70, label: 'Arrow 2', rotation: '180', arrowcolor: '#e71c1d'}] var svg = d3.select('svg'); for(let d of data){ var line = svg.append("line") .attr("d", "line_path") .attr("x1",d.x1) .attr("y1",d.y1) .attr("x2",d.x2) .attr("y2",d.y2) .attr("stroke", d.arrowcolor) .attr("stroke-width",2) .attr("marker-end", markercolor(d.arrowcolor)) .attr("rotate", d.rotation); var value = d3.select('line'); value.append("text") .attr("dy", 30) .style("text-anchor", "middle") .text(d.label); } function markercolor(color) { svg.append("svg:defs").append("svg:marker") .attr("id", color.toString().replace("#", "")) .attr("refX", 6) .attr("refY", 6) .attr("markerWidth", 30) .attr("markerHeight", 30) .attr("markerUnits","userSpaceOnUse") .attr("orient", "auto") .append("path") .attr("d", "M 0 0 12 6 0 12 3 6") .style("fill", color); return "url(" + color + ")"; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg width="300" height="200"> </svg>

你能帮我解决这个问题吗?

修复它,为任何有同样问题的人发布修复:

for(let d of data){
  var line = svg.append("line")
             .attr("d", "line_path")
             .attr("x1",d.x1)  
             .attr("y1",d.y1)  
             .attr("x2",d.x2)  
             .attr("y2",d.y2)  
             .attr("stroke", d.arrowcolor)  
             .attr("stroke-width",2)  
             .attr("marker-end", markercolor(d.arrowcolor))
             .attr("rotate", d.rotation); 
  
  svg.append("text")
    .attr("dx", (d.x1 + d.x2)/2)
    .attr("dy", d.y1)
    .style("text-anchor", "middle")
    .text(d.label);
}

暂无
暂无

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

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