r - 当美学长度不为 1 或与数据长度相同时,如何在 ggplot2 中绘制线段

标签 r plot ggplot2

我正在尝试使用 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")

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)

编辑:将 color="segment"替换为 color="red",因为 color= "segment"在此示例中没有意义。

正如您可能注意到的,我使用了与基础 R 中的 snippet() 函数相同的逻辑,但 ggplot 提示我的美学长度,因为它将是数据的长度 -1。

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

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)

最佳答案

您应该考虑为这些段构建一个单独的数据框:

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))

关于r - 当美学长度不为 1 或与数据长度相同时,如何在 ggplot2 中绘制线段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148373/

相关文章:

r - 绘制函数和导数函数

r - 根据另一行中的条件聚合 data.table

c++ - 教育 - 使用 Rcpp 理解递归函数的可变性能

python - 从(古代)SAS 版本 6(适用于 Python/R)读取 .ssd01 数据文件

r - 如何在图中指定字体大小(用于 PDF 输出)?

ios - 提高核心情节的表现

r - ggplot2 错误 : Discrete value supplied to continuous scale

r - ggplot2:将 geom_bar 基线设置为 1 而不是零

r - ggplot2 使用开环或闭环

r - 如何计算 data.frame 中的所有唯一值