I did ask some questions last days about loops last days and it helped me a lot, and many thanks to you guys! This time I met, I think, more complex issue. I skipped the labels and some details in plot code, but it works perfectly.
In general I would like to produce lots of plot using loop. I learned how to deal with simple plot like this, but with ggplot and aes I found it more complicated.
Here are the data as .csv on dropbox.
Some preparation:
data <- select(baza,strefa,v1,v2,v3,v4,v5,v6,v7,v8) # with dplyr package
strefa <- data$strefa
data$strefa <- NULL
data <- data.frame(apply(data, 2, function(x) {x <- recode(x, "9=NA"); x})) #with car package
Some summarize for aes: a <- data$v1 df <- data.frame(cbind(a,strefa))
srednie <- aggregate(a ~ strefa, data = df, FUN = mean)
GD.mean <- round(mean(a, na.rm = TRUE), digits = 2)
srednie <- rbind(srednie, c(13,GD.mean))
And ggplot code:
jpeg(paste0("plot_",names(data)[i],".jpg"),
width = 166, height = 120, units = "mm", pointsize = 12,
res = 300, quality = 90)
ggplot(srednie, aes(x=factor(strefa), y=a, label=round(srednie$a, digits = 2))) +
geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.5) +
theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
geom_text(size = 4, hjust = 1.2) +
coord_flip(ylim = c(1,6))
dev.off()
How to bind it into for loop? Should it be in one loop or maybe some more?
for (i in 1:length(names(data))) {
df <- data.frame(cbind(i,strefa))
srednie <- aggregate(i ~ strefa, data = df, FUN = mean)
GD.mean <- round(mean(i, na.rm = TRUE), digits = 2)
srednie <- rbind(srednie, c(13,GD.mean))
jpeg(paste0("plot_",names(data)[i],".jpg"),
width = 166, height = 120, units = "mm", pointsize = 12,
res = 300, quality = 90)
ggplot(srednie, aes(x=factor(strefa), y=i, label=round(srednie$i, digits = 2))) +
geom_bar(position=position_dodge(), stat="identity", fill="#fff68f", colour="darkgrey", width = 0.5) +
theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.ticks.y = element_blank()) +
geom_text(size = 4, hjust = 1.2) +
coord_flip(ylim = c(1,6))
dev.off()
}