2017-06-13 86 views
1

我想从ggplot2输出多个图表。我发现了很好的例子,但仍然找不到我想要达到的目标。for ggplot2中的回路问题

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

通过使用类似于例子,我只希望输出每个物种到目前为止我输出相同的三个组合曲线图三种不同的图形。

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() 
} 

我错过了什么?

enter image description here

+2

如果你试图让一个单独的图形为Species'的'每个级别在循环的每次迭代中都需要使用数据集的适当子集。 [这里是如何](https://stackoverflow.com/a/19147917/2461552)我以前做过这样的工作。 – aosmith

+0

您是否考虑过使用方面而不是创建三个独立的地块? – Uwe

回答

2

你没有过滤数据集for-loop内,所以在同一图形重复三次没有变化。

注意这里的变化:

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 
} 

寻址OP更新,这个工作对我来说:

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 
} 
+0

我还有一个问题。当我添加'geom_rect(data = Coeff,aes(fill = Enc),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.5)'我得到一个错误! plot_list [[i]]中的错误:下标越界。请检查填充数据的OP。 – Alexander

+0

你能看看我最后的评论吗? – Alexander

+0

是在这个可重复的例子它的作品!但在我的真实数据中并没有。我还没弄明白原因是什么! – Alexander