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

2
  • 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 I've done this sort of work before. Commented Jun 13, 2017 at 21:16
  • Have you considered to use facets instead of creating three separate plots? Commented Jun 16, 2017 at 10:59

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Did you able you look at my last comment?
Yes in this reproducible example its works! but in my real data it doesn't. I havent figured out what the reason is!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.