r - 带循环的多个数据帧上的 Ggplot

标签 r loops ggplot2

我试图在具有不同值的相同变量的多个数据帧上绘制相同的图表。我有 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。有谁知道我的代码有什么问题,或者是否有一些更简单的方法来绘制多个数据帧?提前致谢!

最佳答案

您的问题不在于数据帧列表的迭代,而在于 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"))
}

关于r - 带循环的多个数据帧上的 Ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66054201/

相关文章:

r - 以最有效的方式获取间隔期间的事件数

在 R 中逐行重新排序数据帧的列

ios - 填充 365 的数组

c++ - 使用 For 循环对队列进行入队和出队 - C++

JavaScript 最长公共(public)子序列

r - 如何使用 R 中作为函数参数提供的变量名来命名图形的标题?

R - 如何有条件地为 data.frame 的值着色并绘制图表

r - 如何计算大型数据集中出现的次数

r - 使用 ggplot2 将每个第 N 轴标签加粗

r - 使用 ggplot 对 y 轴上的数据进行排序