美文网首页
处理报错:ggplot2折线图报错,不出折线,没有线,成点图了?

处理报错:ggplot2折线图报错,不出折线,没有线,成点图了?

作者: 努力学习的消炎药 | 来源:发表于2023-08-01 09:44 被阅读0次

    师姐让画一个关于动物体重随时间变化的折线图,不会用prism,所以就用R ggplot2 去画
    函数代码很简单
    ggplot(dat_se, aes(x=time, y=weight, colour =group,linetype = group2 ))+ geom_line()
    但是画图的时候出现了一个报错
    geom_line(): Each group consists of only one observation. !Do you need to adjust the group aesthetic?
    然后我的图出现了错误,本来分好的折线图,按照日期,会出现折线的,但是,总画不出折线,成了一个一个柱子的散点图了,烦死了。
    测试别人的数据,和我的一模一样,但是我的就画不出线,急死个人
    代码如下

    library(ggplot2)
    ggplot(dat_se, aes(x=time, y=weight, colour =group,linetype = group2 )) +  
      geom_errorbar(aes(ymin=weight-se, ymax=weight+se), width=.1) +
      scale_color_manual(values = cbPalette)+ geom_line() + geom_point()+
      theme_bw()+ labs(title = '',x = 'Time (days)',y = 'Weight (g)')+
      RotatedAxis()
    

    数据结构如下


    出图像这样



    出现的报错如下



    搞了好久都查不出原因,搜到别人的代码,
    image.png

    别人的能画出来,我的就不可以。数据结构一模一样的dataframe
    搜索了良久,搜到一个解释,是可以的,链接如下,无需梯子。
    https://www.programmingr.com/r-error-messages/geom_path-each-group-consists-of-only-one-observation-do-you-need-to-adjust-the-group-aesthetic/
    大致的意思就是,我所使用的日期,即横坐标,不是一个连续的变量,需要转换成为一个连续的变量,
    1.要是日期的话,就得转换成日期的形式,可以先用
    as.Date(paste0('2023-',substr(dat_se$time,1,2),'-',substr(dat_se$time,3,4)))
    字符串处理后,生成类似于‘2023-07-25’,然后as.Date()转换成日期,就可以出图了
    2.也可以计算成为一个numeric,然后再画图。也可以处理出图。我都测试了,均可以。
    选择了转换成处理后的天数dat_se$time3 = as.numeric(dat_se$time2 - as.Date('2023-05-26'))
    结构如下:

    rm(list = ls())
    library(ggplot2)
    library(reshape2)
    library(Rmisc)
    library(ggpubr)
    library(Seurat)
    library(stringr)
    library(RColorBrewer)
    
    cbPalette = brewer.pal(10,'Set3')
    ggplot(dat_se, aes(x=time3, y=weight, colour =group,linetype = group2 )) +   # group = 1 一定不能忘 
      geom_errorbar(aes(ymin=weight-se, ymax=weight+se), width=.1) +
      scale_color_manual(values = cbPalette)+ geom_line() + geom_point()+
      theme_bw()+ labs(title = '',x = 'Time (days)',y = 'Weight (g)')+
      RotatedAxis()
    ggsave(filename = 'Yourname.pdf',width = 8,height = 6)
    

    代码很烂,基本上参考不出来个啥动动,最主要的是想办法,把你的分组转换成为连续的变量,时间,数字,均可,否则,这个折线图出来就很怪异。
    希望能解决你的困惑~

    相关文章

      网友评论

          本文标题:处理报错:ggplot2折线图报错,不出折线,没有线,成点图了?

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