r - 连接误差线的平均点

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

错误:

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?

最佳答案

如果您在 ggplot 调用中按 group 删除分组,并在对 geom_line 的调用中设置 x = as.numeric(group ) ,它的工作原理。

另外,您不需要在 geom_line

中重新引用 data1
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)

enter image description here

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

编辑 - 带有字母因子标签

这将与 alphabetic 因子标签一起使用,因为因子是由 R 内部编码的方式(即 as.numeric(factor) 返回数字而不是因子标签)

即.e

将组更改为 abc

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)

enter image description here

关于r - 连接误差线的平均点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12504721/

相关文章:

r - 当多个节点具有相同名称时将 XML 解析为 R

r - ivot_wider 导致 "! Can' t 不存在的子集列。“R 中的错​​误

r - 省略 `huxreg` 中的因子变量

r - 奇怪的 geom_path 行为

r - 在 ggplot 中,如何创建带有尖边(如 "toothpicks")的线条可视化?

r - 为坐标选择正确的正则表达式

r - 人名去大写(考虑 ' 和 -)

r - ggplot和R : Two variables over time

r - 如何将抖动添加到 ggpairs 中的散点图矩阵?

r - 使用两个属性的组合频率直方图