【发布时间】:2018-06-17 07:38:30
【问题描述】:
我正在尝试使用 ggplot2 绘制线段,以制作最小生成树 (MST) 的示例。
我可以使用基础 R 来做到这一点,但在尝试使用 ggplot2 增强我的情节时遇到问题。
我有以下例子:
带基础 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")
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)
编辑:将 colour="segment" 替换为 colour="red",因为 colour="segment" 在此示例中没有意义。
您可能注意到,我使用了与 base 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)
【问题讨论】: