I want to make multiple histogram plots (one for each column) in a data frame using a 'for' loop in R. The sample data (df) looks like as follows.
> dput(head(df))
structure(list(Hockey = c(0.03, 0.032, 0.07, 0.033, 0.076, 0.064
), Cricket = c(0.003, 0.004, 0.009, 0.004, 0.009, 0.008), Tennis = c(0.004,
0.006, 0.003, 0.002, 0.002, 0.011), Badminton = c(27.1, 28.7,
28.7, 29.4, 31, 33.6), Groups = structure(c(1L, 1L, 1L, 1L, 1L,
1L), .Label = c("TeamA", "TeamB", "TeamC"), class = "factor")), row.names = c("Participant1",
"Participant2", "Participant3", "Participant4", "Participant5",
"Participant6"), class = "data.frame")
I have already done my online search and I managed to get this code. For each column, I want to make multiple histograms based on 'Groups'. This works for me when I do it without a 'for' loop and for one single column. However, when I try to do it using a 'for' loop all at ones for all columns in 'one single pdf', then the pdf file does get generated without any errors. But it does not produce any plots. Can anyone help me with knowing as to what I might be missing in the code? I just want to make this automated because I have much more than these 4 variables to make such plots for.
library(purrr)
library(ggplot2)
library(doBy)
setwd("C:\\Path\\")
df <- read.table("Histograms_Example.txt", header=T)
pdf(file=paste0("one.pdf"))
par(mfrow = c(1, 1))
loop.vector <- names(df)[1:4]
for (i in loop.vector) {
x <- df[,i]
mu <- summaryBy(x ~ Groups, data = df,
FUN = list(median), na.rm = TRUE)
ggplot(df, aes(x=x, color=Groups, fill=Groups)) +
geom_histogram(aes(y=..density..), position="identity", alpha=0.5)+
geom_density(alpha=0.6)+
geom_vline(data=mu, aes(xintercept=x.median, color=Groups),
linetype="dashed")+
scale_color_grey()+
scale_fill_grey() +
labs(title="Weight histogram plot",x=paste("",x), y = "Density")+
theme_classic()
}
dev.off()
Thanking you.