I created a sankey diagram using plotly and R with three columns. I want to add text on the links, so that you see the value of the links without the need to hover over them. Here's some sample code. I tried out annotations but could not get it to work.
# Create data.table with counts
dt <- dt[, .N, by=c("column_a", "column_b", "column_c"]
# Create nodes
nodes <- c(unique(dt$column_a), unique(dt$column_b), unique(dt$column_c))
# Create links
links <- data.table(
source=c(match(dt$column_a, nodes)-1, match(dt$column_b, nodes)-1),
target=c(match(dt$column_b, nodes)-1, match(dt$column_c, nodes)-1),
value=c(dt$N, dt$N)
# Collapse links
links <- links[, .("value" = sum(value)), by=c("source", "target")]
# Plot Sankey diagram
fig <- plot_ly(
type="sankey",
orientation="h",
node=list(
label=nodes
),
link = links)
# create annotations for flows
annotations <- list()
for (i in 1:nrow(links)) {
source_x <- # x-coordinate of source node
source_y <- # y-coordinate of midpoint of source node
target_x <- # x-coordinate of target node
target_y <- # y-coordinate of midpoint of target node
label <- links$value[i] # create label
annotations[[i]] <- list(
x = (source_x + target_x) / 2, # x-coordinate of annotation
y = (source_y + target_y) / 2, # y-coordinate of annotation
text = label, # set text to label
showarrow = FALSE # hide arrow
)
}
# add annotations to plot
fig <- fig |> layout(
annotations = annotations
)
I tried out looping over the links and add an annotation to each but struggled to find the right coordinates of each link. How do I extract the coordinates of the links of a plotly sankey diagram? Furthermore, when the user changes the position of the nodes (and links), the text should stick to their labels.