1

I would like to output multiple graphs from ggplot2. I found very nice examples but still could not find what I want to achieve.

r-saving-multiple-ggplots-using-a-for-loop

by using similar example, I only want to output three different graphs for each species so far I am outputting same three combined graph.

library(dplyr)

    fill <- iris%>%
      distinct(Species,.keep_all=TRUE)

    plot_list = list()
    for (i in 1:length(unique(iris$Species))) {
      p = ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) +
        geom_point(size=3, aes(colour=Species))
  geom_rect(data=fill,aes(fill = Petal.Width),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.5)+   ## added later to OP

      plot_list[[i]] = p
    }

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:3) {
  file_name = paste("iris_plot_", i, ".tiff", sep="")
  tiff(file_name)
  print(plot_list[[i]])
  dev.off()
}

What I am missing?

enter image description here

Alexander
  • 4,527
  • 5
  • 51
  • 98
  • 2
    If you are trying to make a separate graph for each level of `Species`, you'll need to use the appropriate subset of the dataset in each iteration of the loop. [Here is how](https://stackoverflow.com/a/19147917/2461552) I've done this sort of work before. – aosmith Jun 13 '17 at 21:16
  • Have you considered to use facets instead of creating three separate plots? – Uwe Jun 16 '17 at 10:59

1 Answers1

2

You are not filtering the dataset inside the for-loop, and so the same graph is repeated three times without change.

Note the changes here:

plot_list = list()
for (i in unique(iris$Species)) {
  p = ggplot(iris[iris$Species == i, ], aes(x=Sepal.Length, y=Sepal.Width)) +
    geom_point(size=3, aes(colour=Species))
  plot_list[[i]] = p
}

Addressing the OP update, this works for me:

fill <- iris %>%
  distinct(Species, .keep_all=TRUE)

for (i in unique(iris$Species)) {
  p = ggplot(iris[iris$Species == i, ], aes(x=Sepal.Length, y=Sepal.Width)) +
    geom_rect(data = fill, aes(fill = Petal.Width),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.5) +
    geom_point(size = 3, aes(colour = Species))
  plot_list[[i]] = p
}
GGamba
  • 13,140
  • 3
  • 38
  • 47
  • I have one more issue. When I add `geom_rect(data=Coeff,aes(fill = Enc),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.5)` I am getting an error! Error in plot_list[[i]] : subscript out of bounds. Please check OP for fill data. – Alexander Jun 13 '17 at 23:50
  • Did you able you look at my last comment? – Alexander Jun 14 '17 at 17:28
  • Yes in this reproducible example its works! but in my real data it doesn't. I havent figured out what the reason is! – Alexander Jun 14 '17 at 18:22