What's an idiomatic way to add labels to edges? #3751
Unanswered
hamirmahal
asked this question in
Q&A
Replies: 1 comment 1 reply
-
To address the question, you can achieve this by adding a key-value pair to the edge objects to serve as the label. Declare a variable called "edgeText" and use it to position the labels. Here's an example code: const edges: [
{
source: 1,
target: 2,
label: 'test',
},
{
source: 2,
target: 3,
label: 'explain',
}
....
]
const edgeText = svg.append('svg:g').selectAll('g.linklabelholder').data(edges);
edgeText
.enter()
.append('g')
.attr('class', 'linklabelholder')
.append('text')
.attr('class', 'linklabel')
.style('font-size', '12px')
.style('font-weight', 'bold')
.attr('x', '70')
.attr('dy', '-5')
.attr('startOffset', '50%')
.attr('text-anchor', 'middle')
.style('fill','#000000')
.append('textPath')
.attr('xlink:href', function (_, i) {
return '#linkId_' + i;
})
.text(function (d) {
return `${d.total_transitions}`;
});
edge.attr('d', function (d: any) {
const x1 = d.source.x;
const y1 = d.source.y;
let x2 = d.target.x;
let y2 = d.target.y;
// node pointing with self pointing edge
if (x1 === x2 && y1 === y2) {
const dx = x2 - x1,
dy = y2 - y1,
dr = Math.sqrt(dx * dx + dy * dy);
// Defaults for normal edge.
let drx = dr;
let dry = dr;
const xRotation = 0; // degrees
const largeArc = 1; // needs to be 1
const sweep = 1; // 1 or 0, Change sweep to change orientation of loop.
// Make drx and dry different to get an ellipse
// instead of a circle.
drx = 40;
dry = 15;
// For whatever reason the arc collapses to a point if the beginning
// and ending points of the arc are the same, so kludge it.
x2 = x2 + 1;
y2 = y2 + 1;
// todo fix the path so it will be adjust to the arrow
return (
'M' +
x1 +
',' +
y1 +
'A' +
drx +
',' +
dry +
' ' +
xRotation +
',' +
largeArc +
',' +
sweep +
' ' +
x2 +
',' +
y2
);
} else {
// for applying the curve in our line (edge)
const mid: any = [(d.source.x + d.target.x) / 2, (d.source.y + d.target.y) / 2];
return lineGenerator([[d.source.x, d.source.y], mid, [d.target.x, d.target.y]]);
}
});
edgeText
.attr('x', function (d: any) {
return d.x;
})
.attr('y', function (d: any) {
return d.y;
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This is what I have currently.
It'd be nice if the edge from
0
to3
could display the weight of that edge, but I'm not sure how to do that after looking through the documentation.Beta Was this translation helpful? Give feedback.
All reactions