当美学的长度不是数据长度1或长度时,如何在ggplot2中绘制线段

时间:2018-01-08 10:28:03

标签: r plot ggplot2

我'我试图用ggplot2绘制线段,以便举例说明一个Miniminum生成树(MST)。

我能用基地R做到这一点,但是我能做到这一点。在尝试使用ggplot2增强我的情节时遇到问题。

我有以下示例:

w / base R

# simulating data
n=10
set.seed(1984)
d1<-matrix(rnorm(n,mean=2,sd=1), n/2, 2)
d2<-matrix(rnorm(n,mean=-2,sd=.5), n/2, 2)
d<-rbind(d1,d2)

# starting and ending points
from<-c(1,1,2,2,4,6,7,7,10)
to<-c(5,2,3,4,6,7,9,10,8)

# plot
plot(d[,1:2])
segments(d[from,1], d[from,2], d[to,1], d[to,2],col="blue")

enter image description here

w / ggplot2

df<-as.data.frame(d)
library(ggplot2)
b <- ggplot(df, aes(df[,1], df[,2])) + geom_point()
b + geom_segment(aes(x = df[from,1], y = df[from,2],
               xend = df[to,1], yend = df[to,2]), colour="red", data = df)

修改:替换颜色=&#34;段&#34; by color =&#34; red&#34;,因为color =&#34; segment&#34;在这个例子中没有意义。

正如您可能注意到的那样,我使用了来自基础R的segments()函数中的相同逻辑,但ggplot抱怨我的美学长度,因为它将是数据的长度-1。

  

错误:美学必须是长度1或与数据(10)相同:x,y,xend,yend,color

http://ggplot2.tidyverse.org/reference/geom_segment.html中,逻辑似乎是有效的,但我仍然不知道如何处理美学长度问题。

我已经在Stack Overflow中阅读了其他相关问题,但我无法找到问题的解决方案,因为我的美学不会有相同的数据长度。

相关问题:

Aesthetics must be either length 1 or the same as the data (207): x, y

Error: Aesthetics must be either length 1 or the same as the data (10): x, y

Aesthetics must be either length 1 or the same as the data (1)

2 个答案:

答案 0 :(得分:3)

您应该考虑为细分构建一个单独的数据框:

dfseg <- data.frame(V1=df[from,1], V2=df[from,2], xend=df[to,1], yend=df[to,2])
ggplot(df, aes(V1,V2)) + geom_point() + geom_segment(data=dfseg, aes(xend=xend, yend=yend))

答案 1 :(得分:1)

你几乎拥有它。 fromto包含9个元素,您的数据包含10个元素。我向fromto添加了一个(无用的)第十个元素。那么你的代码工作正常。

from <- c(1, 1, 2, 2, 4, 6, 7, 7, 10, 10)
to <- c(5, 2, 3, 4, 6, 7, 9, 10, 8, 10)

b <- ggplot(df, aes(V1, V2)) + geom_point()
b + geom_segment(aes(
 x = df[from, 1],
 y = df[from, 2],
 xend = df[to, 1],
 yend = df[to, 2],
 colour = "segment"
), data = df)

其中给出了以下情节

enter image description here

旁注:为什么colour = "segment"