修改ggplot中的向外标签位置-避免节点和标签之间重叠 最小示例:

问题描述

外部位置几乎可以满足我在网络中的需求(左侧标签在左侧,右侧在右侧)。@H_502_1@

但是我想对其稍加修改,以免与节点重叠。我尝试在gtable(ggplot_buildggplot_gtable)中搜索修改不成功的内容。在gtable中,标签的位置显示outwards,而不是我可以修改的数字。@H_502_1@

即使我将outwards更改为其他选项,我也只会看到对齐的符号值而不是实际位置值。@H_502_1@

最小示例:

#
#   matrix
#
myvec<-structure(list(lengths = c(1L,2L,27L,1L,6L,15L,23L,4L,77L,22L,21L,3L,30L,38L,40L,12L,8L,9L,28L,31L,5L,10L,25L,16L,20L
),values = c(0,1,0)),class = "rle")

mymat <- structure(unlist(mapply(rep,myvec$values,myvec$lengths) ),.Dim = c(26L,26L),.Dimnames = list(NULL,NULL) )

colnames(mymat)  <- paste("name",1:ncol(mymat))
row.names(mymat) <- paste("name",1:nrow(mymat))

#
# network
#

library(network)
net1 <- network(mymat,matrix.type = "adjacency",ignore.eval = FALSE,directed=T
)

#
#   Custom position of nodes
#

finalxy<-structure(c(-2,6,2,4,-6,-4,8,-2,10,4),2L) )

net1 %v% "xpos" = finalxy[,1]
net1 %v% "ypos" = finalxy[,2]

#
# edges 
#
library(ggnetwork)
library(dplyr)

networkdata <- sapply(net1$mel,function(x) 
  c('id_inl' = x$inl,'id_outl' = x$outl,'weight' = x$atl$weights)) %>%
  t %>% as_tibble()

posxyOrig<-finalxy[networkdata$id_outl,]
posxyTarg<-finalxy[networkdata$id_inl,]

colnames(posxyOrig)<-c("xorig","yorig")
colnames(posxyTarg)<-c("xtarg","ytarg")

posData1<-cbind(networkdata,posxyOrig,posxyTarg )

#
# modify arrows (edges) to avoid overlap
#

posData1$xtarg <- ifelse(posData1$xorig>posData1$xtarg,posData1$xtarg+.2,ifelse(posData1$xorig==posData1$xtarg,posData1$xtarg,posData1$xtarg-.2
                        )
)

posData1$ytarg <- ifelse(posData1$yorig>posData1$ytarg,posData1$ytarg+.2,ifelse(posData1$yorig==posData1$ytarg,posData1$ytarg,posData1$ytarg-.2
                        )
)

#
#   plot
#

ggplot(net1 )+
  geom_edges(data=posData1,aes(x = xorig,y = yorig,xend = xtarg,yend = ytarg),arrow = arrow(length = unit(10,"pt"),type = "closed")
  ) +
  geom_nodes(aes(x=xpos,y=ypos ),size = 4) +
  geom_nodelabel(aes(x=xpos,y=ypos,label = vertex.names  ),hjust="outward",vjust="outward",fontface = "italic",size=3
  ) + theme_blank()

this post @H_502_1@

编辑

使用格雷格雷开发。版本geom_nodelabel_repel效果更好,但标签看上去并不“向外” @H_502_1@

# related to https://stackoverflow.com/questions/56028991/override-horizontal-positioning-with-ggrepel
# using ggrepel devel. version

ggplot(net1 )+
geom_edges(data=posData1,size = 4) +
  geom_nodelabel_repel(aes(x=xpos,size=3
  ) + theme_blank()

@H_502_1@

解决方法

解决方案: 使用ggrepel,devel版本,然后向外更改为向内

devtools::install_github("slowkow/ggrepel")

ggplot(net1 )+
  geom_edges(data=posData1,aes(x = xorig,y = yorig,xend = xtarg,yend = ytarg),arrow = arrow(length = unit(10,"pt"),type = "closed")
  ) +
  geom_nodes(aes(x=xpos,y=ypos ),size = 4) +
  geom_nodelabel_repel(aes(x=xpos,y=ypos,label = vertex.names  ),hjust="inward",vjust="inward",fontface = "italic",size=3
  ) + theme_blank()

enter image description here