连接误差线的均值点

Tyl*_*ker 2 r ggplot2

在 ggplot2 中,我正在尝试一件简单的事情,但由于某种原因我无法做到。我已经在数据框中调整了均值和 SE,想要绘制均值、误差线,然后将均值与点连接起来。这是代码和错误(除了将手段连接到geom_line(使用RCookbook

library(ggplot2)
#data set
data1 <- structure(list(group = structure(1:3, .Label = c("1", "2", "3"
), class = "factor"), estimate = c(55.7466654122763, 65.0480954172939, 
61.9552391704298), SE = c(2.33944612149257, 2.33243565412438, 
2.33754952927041), t.ratio = c(23.8290016171476, 27.8884844271143, 
26.5043535525714)), .Names = c("group", "estimate", "SE", "t.ratio"
), row.names = c(NA, 3L), class = "data.frame")

#the attempted plot
pd <- position_dodge(.1)
ggplot(data1, aes(x=group, y=estimate, group=group)) + 
    geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
        colour="black", width=.1, position=pd) +
    geom_line(data=data1, aes(x=group, y=estimate)) + 
    geom_point(position=pd, size=4)
Run Code Online (Sandbox Code Playgroud)

错误:

ymax not defined: adjusting position using y instead
geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?
Run Code Online (Sandbox Code Playgroud)

mne*_*nel 5

如果您group在 ggplot 调用中删除分组并在调用中设置 x = as.numeric(group )geom_line,则它可以工作。

此外,您不需要data1在内部重新引用geom_line

ggplot(data1, aes(x=group, y=estimate)) + 
  geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
  colour="black", width=.1, position=pd) +
  geom_line( aes(x=as.numeric(group), y=estimate)) + 
  geom_point(position=pd, size=4)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果您是groupby group,那么您只有一个值geom_line来创建一行,因此会出现错误消息。如果ggplotxy映射变量视为因子,则会发生相同的错误- 这是因为如果将变量编码为因子 R(和 ggplot)会将它们视为独立的组,而不是连接点 - 这是明智的默认行为。

编辑 - 带有字母因子标签

由于因子内部编码的方式,这将适用于字母因子标签R (即 as.numeric(factor) 返回数字而不是因子标签)

将组更改为a, b,c

levels(data1[['group']]) <- letters[1:3] 
ggplot(data1, aes(x=group, y=estimate)) + 
  geom_errorbar(aes(ymin=estimate-SE, ymax=estimate+SE), 
  colour="black", width=.1, position=pd) +
  geom_line( aes(x=as.numeric(group), y=estimate)) + 
  geom_point(position=pd, size=4)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明