I am fairly new to d3.js and I have created two arrows in the d3 graph and I am trying to add the text in the center of the arrows, but I am unable to see the labels getting added to the arrows.
My codepen link is below:
https://codepen.io/Navin_Kris/pen/mdXwVoY
The code is as follows
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>
Could you please help me out on this.
Fixed it , posting the fix for anyone who will have same issue:
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.