for loop issue in ggplot2

2019-06-07 06:58发布

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

1条回答
家丑人穷心不美
2楼-- · 2019-06-07 07:37

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
}
查看更多
登录 后发表回答