我试图在具有不同值的相同变量的多个数据帧上绘制相同的图表。我有 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/