【问题标题】:Using apply function on a list to get plots在列表上使用应用函数来获取图
【发布时间】:2021-02-04 02:39:08
【问题描述】:

我可以在一个数据集上绘制图表,但在 lapply 上遇到问题。这是我的代码:首先获取统计信息,然后绘制统计信息。

stats1<- data %>%
  group_by(Group,ERF) %>%
  summarize(mean=mean (Latency),
            sd = sd(Latency),
            sem = sd(Latency)/sqrt(n()),
            n = n())
ggplot(stats1,aes(x=ERF,y=mean,fill=Group))+ geom_bar(stat="identity",position="dodge")+
  geom_errorbar(aes(ymin = mean - sem, ymax = mean + sem),                            
                width = 0.2)

上面的代码有效。下面是使用 lapply 和 splitlist 的代码

splitlist=split(data,data$Group)
stats<-lapply(splitlist,function(x){mean=mean(x$Latency)
                             sd = sd(x$Latency)
                             sem = sd(x$Latency)/sqrt(length(x$Latency))
                             })
lapply(splitlist,function(x) ggplot(data=x,aes(ERF,mean,fill=Group))+ geom_bar(stat="identity",position="dodge")+
        geom_errorbar(aes(ymin = mean - sem, ymax = mean + sem),                            
                      width = 0.2)

stats 只返回 mean 而不是 sem;那么这里是ggplot的错误 不知道如何为函数类型的对象自动选择比例。默认为连续。 错误:美学必须是有效的数据列。有问题的美学:y = 平均值。 您是否输入错误的数据列名称或忘记添加 after_stat()?

如何修复错误并从每个数据列表中获取图表?谢谢!

【问题讨论】:

    标签: r loops


    【解决方案1】:

    reproducible example 会很有帮助。

    您应该在相同的lapply 代码中计算统计数据和绘图,但是您不需要重新计算统计数据,因为您已经在stats1 中拥有它。 split stats1 基于 Group 并使用该数据进行绘图。

    library(ggplot2)
    
    splitlist = split(stats1,stats1$Group)
    
    lapply(splitlist,function(x) {
      ggplot(data=x, aes(ERF,mean)) + 
        geom_bar(stat="identity",position="dodge")+
        geom_errorbar(aes(ymin = mean - sem, ymax = mean + sem), width = 0.2)
    }) -> list_plots
    
    list_plots
    

    【讨论】:

    • 如此优雅。拆分统计数据,就是这样!
    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2014-12-26
    • 2021-09-20
    相关资源
    最近更新 更多