【问题标题】:Ggplot over multiple dataframes with loops带有循环的多个数据帧上的ggplot
【发布时间】:2021-05-09 06:13:53
【问题描述】:

我正在尝试在具有不同值的相同变量的多个数据帧上绘制相同的图表。我有 n 个名为 df_1、df_2 ... df_n 的数据帧,我的代码如下所示:

#Create dataframes(In this example n = 3)
df_1 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)  
df_2 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)
df_3 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)

##Store dataframes in list
example.list<-lapply(1:3, function(x) eval(parse(text=paste0("df_", x)))) #In order to store all datasets in one list using their name
names(example.list)<-lapply(1:3, function(x) paste0("df_", x))

#Graph and save for each dataframe
for (i in example.list){
  benp <-  ggplot(i, aes(x=b1)) + 
    geom_histogram(fill="steelblue", aes(y=..density.., alpha=..count..), bins=60) + 
    labs(title="Beneficios", subtitle="") + ylab("Densidad") + 
    xlab("Beneficios ($millones)") + 
    geom_vline(aes(xintercept=mean(b1)), color="red4",linetype="dashed") +
    theme(legend.position = "none") + 
    annotate("text", x= mean(b1), y=0, label=round(mean(b1), digits = 2), 
             colour="red4", size=3.5, vjust=-1.5, hjust=-0.5) 
  ggsave(benp, file=paste0(i,"_histogram.png"))
}   

我收到错误消息“平均值错误(b1):找不到对象 b1”。我不知道如何告诉 R b1 来自数据帧 i。有谁知道我的代码有什么问题,或者是否有一些更简单的方法可以绘制多个数据帧?提前致谢!

【问题讨论】:

  • 嗨,Andres,您能创建一个可重现的示例来分享吗?
  • 嗨,雷克斯。我改变了我的帖子,所以它可以成为一个可重复的例子
  • 别担心,@Andres。请在下面查看我的回答,如果它适合您,请接受它。

标签: r loops ggplot2


【解决方案1】:

您的问题不在于对数据帧列表的迭代,而在于annotate()b1 的使用。在这里,我在每个循环中创建了一个新的数据框,并专门调用了列名。不过,可能有更好的方法来做到这一点。此外,ggsave() 需要调用列表中项目的名称,具体而言。

library(tidyverse)

#Create dataframes(In this example n = 3)
df_1 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)  
df_2 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)
df_3 <- data.frame(a1 = 1:1000,
                   b1 = 1:1000)

##Store dataframes in list
example.list<-lapply(1:3, function(x) eval(parse(text=paste0("df_", x)))) #In order to store all datasets in one list using their name
names(example.list)<-lapply(1:3, function(x) paste0("df_", x))

#Graph and save for each dataframe

for (i in 1:length(example.list)){
  df_i <- example.list[[i]]
  benp <-  
    df_i %>%
    ggplot(aes(x=b1)) + 
    geom_histogram(fill="steelblue", aes(y=..density.., alpha=..count..), bins=60) + 
    labs(title="Beneficios", subtitle="") + ylab("Densidad") + 
    xlab("Beneficios ($millones)") + 
    geom_vline(aes(xintercept=mean(b1)), color="red4",linetype="dashed") +
    theme(legend.position = "none") + 
    annotate("text", x= mean(df_i$b1), y=0, label=round(mean(df_i$b1), digits = 2), 
             colour="red4", size=3.5, vjust=-1.5, hjust=-0.5) 
  ggsave(benp, file=paste0(names(example.list)[i],"_histogram.png"))
}

【讨论】:

    【解决方案2】:

    get() 函数是您正在寻找的,用于将字符串评估为数据框。

    get() 返回命名对象的值

    例如:

    x <- "iris"
    summary(get(x))
    #  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
    # Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100   setosa    :50  
    # 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300   versicolor:50  
    # Median :5.800   Median :3.000   Median :4.350   Median :1.300   virginica :50  
    # Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199                  
    # 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800                  
    # Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
    

    你的例子:

    #Store dataframes in list
    graph.list<-lapply(1:10, function(x) eval(parse(text=paste0("data_new", x)))) #In order to store all datasets in one list using their name
    names(graph.list)<-lapply(1:10, function(x) paste0("data_new", x))
    
    #Graph and save for each dataframe
    for (i in graph.list){
      benp <-  ggplot(get(i), aes(x=b1)) + 
        geom_histogram(fill="steelblue", aes(y=..density.., alpha=..count..), bins=60) + 
        labs(title="Beneficios", subtitle="") + ylab("Densidad") + 
        xlab("Beneficios ($millones)") + 
        geom_vline(aes(xintercept=mean(b1)), color="red4",linetype="dashed") +
        theme(legend.position = "none") + 
        annotate("text", x= mean(b1), y=0, label=round(mean(b1), digits = 2), 
                 colour="red4", size=3.5, vjust=-1.5, hjust=-0.5) 
      ggsave(benp, file=paste0(i,"_histogram.png"))
    }
    

    【讨论】:

    • 感谢您的回复!当我运行代码时,我收到以下消息:get(i) 中的错误:第一个参数无效。你知道有什么问题吗?再次感谢!
    • 检查 for 循环在做什么...for (i in graph.list){ print(i) }
    • 好的,它会打印graph.list中保存的所有数据框
    • 如果您手动放入 df_1,ggplot 是否在循环之外工作?
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 2022-01-16
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多