jhfodr76
jhfodr76

Reputation: 109

How to draw an arrowhead on a specific position on an edge?

I have a graph in which each edge is an ownership distribution between its nodes. E.g., of the edge between "A" and "B", "A" owns 90% and "B" owns only 10%. I would like to visualize this by placing an arc on the edge in relative position to that ownership. How can I do that? I would prefer using ggraph and using arrows to visualize relative ownership, but I'm open to other suggestions.

By default, arcs are put at the end of an edge. For instance the below creates the following figure.

library(ggraph)
library(ggplot2)

# make edges
edges = data.frame(from = c("A", "B", "C"),
                   to = c("C","A", "B"),
                   relative_position = c(.6,.1, .4))

# create graph
graph <- as_tbl_graph(edges)

# plot using ggraph
ggraph(graph) + 
  geom_edge_link(
    arrow = arrow()
  ) + 
  geom_node_label(aes(label = name))

enter image description here

What I want is something like the below. I found this discussion to shift the arrows to the center of an edge, but as far as I can see, that approach won't work for setting a relative position.

enter image description here

Upvotes: 0

Views: 206

Answers (1)

Kyle Kimler
Kyle Kimler

Reputation: 46

I suggest overlaying two geom_link_edges - the first with the full link between nodes, and the second with the partial link that has an arrow at the end. I was able to achieve this with your example like so:

library(ggraph)
library(ggplot2)

# make edges
edges = data.frame(from = c("A", "B", "C"),
                   to = c("C","A", "B"),
                   relative_position = c(.6,.1, .4))

# create graph
graph <- as_tbl_graph(edges)

# plot using ggraph
ggraph(graph) + 
  geom_edge_link() +
  #this the partial link with the arrow - calculate new end coordinates
  geom_edge_link(aes(xend=((xend-x)*relative_position)+x,
                     yend=((yend-y)*relative_position)+y)
                  arrow = arrow()) + 
  geom_node_label(aes(label = name))

Upvotes: 1

Related Questions