yan wang
yan wang

Reputation: 141

How to rotate the labels to make their orientation consistent with the edges using igraph in R?

I am trying to plot a network using igraph in R. Each edge in the network has a label. I would like to make each label have a same orientation with its edge. Here is my code.

##
library(igraph)

###Data
id <- c("CO1", "CO2", "CO3", "CO4", "CO5", "CO6", "CO7")
id.type <- c("0", "1", "1", "0", "0", "1", "0")
y <- c("0", "7.2", "-0.8", "7", "6.8", "2", "-1")
x <- c("-0.25", "-4", "-2.5", "-4", "-4", "-0.5", "-2.2")
nodes <- data.frame(id=id, id.type=id.type, id_y=y, id_x=x)#把data.frame变成list,就是创建list

from <- c("CO1", "CO2", "CO1", "CO3", "CO4", "CO1", "CO6")
to <- c("CO5", "CO1", "CO6", "CO7", "CO2", "CO4", "CO7")
l <- c("1.1.1.34; 1.1.1.88", "1.13.11.3", "2.3.3.9", "2.1.1.6", "6.3.2.1", "2.6.1.44; 2.6.1.45", "4.4.5.7")
w1 <- c(296.06,30.88,476.31,120.51,206.6,260.56,160.56)
w <- array(c(w1),dim = c(7,1,1))
links <- data.frame(from=from, to=to, type=l, weight=w)

##get the network
net <- graph_from_data_frame(d=links, vertices=nodes, directed=T)
l <- layout_as_tree(net)
l <- norm_coords(l, ymin=-2, ymax=8.5, xmin=-5.5, xmax=2.5)

plot(net, layout=l, 
          edge.arrow.size=abs(log(links$weight,120))*1.3,
          edge.label=links$type,
          edge.label.cex=abs(log(links$weight,120))*0.8,
          edge.width=abs(log(links$weight,120))*5)

Its results: Network of mine now

I want to rotate the labels to make their orientation consistent with the edges. Just like this : enter image description here

Could anyone help me? Thanks a lot.

Upvotes: 1

Views: 293

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

I'm not sure this is possible within the basic igraph plot. There are a huge number of plotting options for graphs if you use the ggraph package though, including on-line edge labels:

library(ggraph)

ggraph(net) + 
  geom_edge_link(aes(label = type, width = weight), 
                 edge_colour = 'gray',
                 angle_calc = 'along',
                 lineend = 'round',
                 label_dodge = unit(2.5, 'mm'),
                 arrow = arrow(length = unit(4, 'mm')), 
                 end_cap = circle(10, 'mm')) + 
  geom_node_circle(aes(r = 0.2), fill = 'orange') +
  geom_node_text(aes(label = name)) +
  theme_graph() +
  scale_edge_width(range = c(0.5, 3), guide = 'none') +
  coord_equal()

enter image description here

Upvotes: 3

Related Questions