【问题标题】:How to plot line segments in ggplot2 when aesthetics do not have length 1 or same length as the data当美学没有长度1或与数据相同的长度时如何在ggplot2中绘制线段
【发布时间】: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)

【问题讨论】:

    标签: r plot ggplot2


    【解决方案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))
    

    【讨论】:

    • 确实,这是一个巧妙的解决方案。谢谢!
    【解决方案2】:

    你几乎拥有它。 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)
    

    这给出了以下情节

    旁注:为什么是colour = "segment"

    【讨论】:

    • 谢谢!好把戏!! colour="segment" 来自 Hadley 在ggplot2.tidyverse.org/reference/geom_segment.html 的示例。但正如您所指出的,这里不相关。我将编辑我的问题,以便让其他用户更清楚。非常感谢您的帮助。
    • 很高兴我能帮上忙。顺便说一句,如果您想为所有段分配单一颜色,请将颜色参数放在 aes() 之外。
    • 这正是我想要的。我已经修复了示例中的代码。感谢您的时间和帮助。
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2017-11-04
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多