在ggplot2中进行分面时如何添加一个条形图?

7

我在R中有一个facet grid ggplot2图,我想为每个facet叠加一条水平线和一个ribbon。我已经分别为水平线和ribbon值制作了单独的数据框。然而,当添加ribbon时,我遇到了'object not found error'的问题。

下面是一些可重复的代码。

# create DF
df1 = data.frame( x = rep(letters[1:4], 4),
              y = rnorm(16, 0 , 1),
              group = rep(1:4, each=4))

# horizonal line DF
hLines = data.frame(group = unique(df1$group) , 
                y = aggregate(y ~ group, data=df1 , FUN=mean)[2] )

# CIs DF
hCIs = data.frame(group = unique(df1$group), 
              low = hLines$y -  (2 * aggregate(y ~ group, data=df1 , FUN=sd)[2] ),
              high = hLines$y + (2 * aggregate(y ~ group, data=df1 , FUN=sd)[2] ) )

ggplot(df1 , aes(x = x , y = y)) +
  facet_grid(~group) +
  geom_point(size=3) +
  geom_hline(data=hLines, aes(yintercept = y))+
  geom_ribbon(data=hCIs, aes(x=x, ymin=low, ymax=high))+
  theme_bw()

当没有包含geom_ribbon命令时,它可以工作。但是当我尝试添加ribbon时,会出现以下错误:

Error in eval(expr, envir, enclos) : object 'low' not found

非常感谢你的帮助。

编辑: 我在hCIs列名中犯了一个错误。然而,当指定以下内容时:

colnames(hCIs) = c("group", "low", "high")

我仍然收到一个错误:

错误:美学必须是长度为1或与数据相同(4):x,ymin,ymax,y


看一下 hCIs,没有叫做 low 的列。 - erc
抱歉,你是对的。在我的原始数据中,列名是相同的。然而,在这个例子中,当我手动指定hCIs中的列名为"group"、"low"和"high"时,我收到了"Error: Aesthetics must be either length 1 or the same as the data (4): x, ymin, ymax, y"的错误提示。 - user3237820
如果我在geom_ribbon中保留x=x,则会出现以下错误:Error in eval(expr, envir, enclos) : object 'x' not found 但如果我使用:geom_ribbon(data=hCIs, aes(group = 1, x = low,ymin=low, ymax=high), inherit.aes=FALSE),则不会出现任何错误,图表将显示。 - Miha
1个回答

8

您的geom_ribbon没有关于x的信息,因为您正在指定一个新的数据源:hCIs,而没有x

但是,如果您将这两个数据框合并以获取每个hCIs数据点的x值,则可以解决此问题:

ggplot(df1 , aes(x = x , y = y)) +
    facet_grid(~group) +
    geom_point(size=3) +
    geom_hline(data=hLines, aes(yintercept = y))+
    geom_ribbon(data=merge(hCIs, df1), aes(ymin=low, ymax=high, group = group), alpha = 0.2)+
    theme_bw()

enter image description here


1
我已经尝试了您的解决方案,不再出现错误消息,但是功能区未显示。我正在使用geom_bar dodge。 - Herman Toothrot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接