【问题标题】:How to position both geom_path and geom_errorbar properly at the same time in ggplot2如何在ggplot2中同时正确定位geom_path和geom_errorbar
【发布时间】:2015-07-13 17:44:20
【问题描述】:

我尝试创建一个同时具有误差条和 p_value 的条形图。但是,我无法正确定位误差条和 p_value 条。这是我的代码:

library(ggplot2)
df = data.frame(a=c('A','A','B','B'),b=c('X','Y','X','Y'),c=c(1,2,3,2),err=c(.1,.2,.1,.2))
q = ggplot(df, aes(a, y=c))+
  geom_bar(aes(fill=b),position=position_dodge(), stat="identity")+
  geom_errorbar(aes(ymin=c-err,ymax=c+err), width=0.3, lwd = 1, position=position_dodge(0.9))


path = data.frame(x=c(1.25,1.75),y=c(3.5,3.5))
q = q + geom_path(data=path,aes(x=x, y=y),size=2)
q = q+ annotate('text',x=1.5,y=4, label='p=0.03')

print(q)

问题似乎是由“填充”参数引起的。如果我将“fill=b”放入 ggplot() 中,它会弄乱 p_value 条的位置。如果我在 geom_bar() 中放入“fill=b”,它会弄乱错误栏的位置。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    geom_errorbar 中添加group=b,以便position_dodge 知道该怎么做

      geom_errorbar(aes(ymin=c-err,ymax=c+err, group=b), width=0.3, lwd = 1, position=position_dodge(0.9))
    

    为了以后参考,你可以直接用ggplot_build访问柱子的位置

    ## Get bar positions
    stuff <- ggplot_build(q)
    dat <- stuff[[1]][[2]]
    

    【讨论】:

    • 谢谢,成功了! ggplot_build 的建议很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2019-07-19
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多