gpt4 book ai didi

r - 在ggplot2中很好地排列点之间的箭头

转载 作者:行者123 更新时间:2023-12-02 17:24:02 27 4
gpt4 key购买 nike

(注意 - 这是与 using multiple size scales in a ggplot 相同的作品,但我问的是不同的问题)

我正在尝试构建一个图来显示从一个类到另一个类的转换。我想要用圆圈代表每个类,从一个类到另一个类的箭头代表转换。

我使用 geom_segment 和 arrow() 来绘制箭头。有没有办法:

  • 让箭头在到达圆圈之前停止
  • 调整位置,以便如果两个方向都有箭头,它们会被“躲避”而不是重叠。

我无法让position="dodge"在这里做任何有用的事情。

举个例子:

library(ggplot2)
points <- data.frame( x=runif(10), y=runif(10),class=1:10, size=runif(10,min=1000,max=100000) )
trans <- data.frame( from=rep(1:10,times=10), to=rep(1:10,each=10), amount=runif(100)^3 )
trans <- merge( trans, points, by.x="from", by.y="class" )
trans <- merge( trans, points, by.x="to", by.y="class", suffixes=c(".to",".from") )
ggplot( points, aes( x=x, y=y ) ) + geom_point(aes(size=size),color="red",shape=1) +
scale_size_continuous(range=c(4,20)) +
geom_segment( data=trans[trans$amount>0.6,], aes( x=x.from, y=y.from, xend=x.to, yend=y.to ),lineend="round",arrow=arrow(),alpha=0.5, size=0.3)

Example graph

最佳答案

我想既然没有人给出解决方案,我会提供一个更针对此类问题的包示例:

vecs  <- data.frame(vecs =1:6,size=sample(1:100,6))
edges <- data.frame(from=sample(1:6,9,replace=TRUE), to=sample(1:6,9,replace=TRUE))

library(igraph)

g <- graph.data.frame(edges, vertices = vecs, directed = TRUE)
coords <- cbind(sample(1:20,6), sample(1:20,6))


plot(g, vertex.size=V(g)$size,vertex.color="white",layout=coords,axes=TRUE)

这至少可以解决圆之前的箭头问题,并且当存在相互箭头时,它会用曲线调整它们,如 2<->5 中所示。 :

enter image description here

(箭头大小、线宽、颜色等当然可以修改)

关于r - 在ggplot2中很好地排列点之间的箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14647988/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com