I am kind of stuck with the for loop in ggplot2.
I am trying to adding Species and categ names to each plot title as well as the file name through the for loop in ggplot2. Somehow, the loop seems to taking only one Species name to title.
library(dplyr)
data_iris <- iris%>%
mutate(categ=ifelse(Petal.Width<0.4,"A",ifelse(Petal.Width>=0.4&Petal.Width<=1.0, "B","C")))
> head(data_iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species categ
1 5.1 3.5 1.4 0.2 setosa A
2 4.9 3.0 1.4 0.2 setosa A
3 4.7 3.2 1.3 0.2 setosa A
4 4.6 3.1 1.5 0.2 setosa A
5 5.0 3.6 1.4 0.2 setosa A
6 5.4 3.9 1.7 0.4 setosa B
PLOT PART
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
p = ggplot(data_iris[data_iris$categ==j,], aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(size=3, aes(colour=categ))+
labs(title=paste( i,j, "species_categ",sep="_")) #this part is not working!!!
plot_list[[j]] = p
}
}
# Save plots to tiff. Makes a separate file for each plot.
library(ggplot2)
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
file_name = paste(i,j, "iris_plot_", ".tiff", sep="_")
tiff(file_name)
print(plot_list[[j]])
dev.off()
}
}
ant the output is like this (I didn't add all plots and names. But you will see them in working directory)
So, as we can see the problem is here I can't get the correct Species name for each plot. I could not get it? Why this is happening ?




plot_list[[j]]you don't account fori, so you're only going to end up with plots for one value ofi, the previous plots will be overwritten. You also don't filter the data based oniat all in your plotting loop, I'm not sure what you were hoping to do with that.Speciesfor too ? How?for (i in unique(data_iris$Species))outer loop at all if you don't actually need to change the data within the loop based oni.Speciesplot subcategory ofcategand putSpeciesandcategnames in the title as well as in the output file. Is this clear ?