美文网首页R
[R] 添加误差棒的分组折线图:geom_path: Each

[R] 添加误差棒的分组折线图:geom_path: Each

作者: 生物信息与育种 | 来源:发表于2019-08-25 23:44 被阅读0次

    想做一个简单的分组折线图,并添加误差棒,类似下面这样的:

    image.png
    用ggplot似乎很简单就能实现:ggplot+geom_errorbar+geom_line+geom_point,重点在于计算误差棒。
    还是看示例数据吧:
    image.png
    Type是转录和蛋白两个组学,Region是某个组织的不同区域。想作如上图的样子,即不同区域在两个组学的折线图分布。

    计算误差需要安装Rmisc包中的summarySE函数。

    # summarySE 计算标准差和标准误差以及95%的置信区间.
    library(Rmisc)
    tgc <- summarySE(df2, measurevar="Abundance", groupvars=c("Type","Region"))
    

    数据变成这样:


    image.png

    接下来就是作图了。

    # 带有标准误差线的折线图
    # Standard error of the mean
    ggplot(tgc, aes(x=Region, y=Abundance, colour=Type)) +   
      geom_errorbar(aes(ymin=Abundance-se, ymax=Abundance+se), width=.1) +
      geom_line() +
      geom_point()
    

    得到警告:

    image.png
    图是这样的,线没有画出来。
    image.png
    查了下网上的答案:https://blog.csdn.net/tanzuozhev/article/details/51106089
    它的数据形式几乎和我的一样,但是却能正常画出来。

    我想了想,是不是分组变量Type和Region没设为因子,但是设了还是一样。

    查了下错误,说是要映射group,令group=1。https://stackoverflow.com/questions/27082601/ggplot2-line-chart-gives-geom-path-each-group-consist-of-only-one-observation
    我这里设置了两组,用group=1或2显然不行,于是将group映射到变量:

    ggplot(tgc, aes(x=Region, y=Abundance, colour=Type, group=Type)) +  
      geom_errorbar(aes(ymin=Abundance-se, ymax=Abundance+se), width=.1) +
      geom_line() +
      geom_point()
    

    果然解决了


    image.png

    但我还是不明白,为啥网上的示例同样是两个分组变量,不用group也能做出来。

    相关文章

      网友评论

        本文标题:[R] 添加误差棒的分组折线图:geom_path: Each

        本文链接:https://www.haomeiwen.com/subject/khfkectx.html