在ggplot2中的循环问题 [英] for loop issue in ggplot2
问题描述
r-saving-multiple-ggplots-using-a-for-loop
使用类似的例子,我只想为每个物种输出三个不同的图,到目前为止我输出的是三张相同的图。
library (dplyr)
填充< - iris%>%
distinct(Species,.keep_all = TRUE)
plot_list = list()
对于(我在1:长度(唯一(虹膜$物种))){
p = ggplot(虹膜,aes(x = Sepal.Length,y = Sepal.Width))+
geom_point(size = aes(fill = Petal.Width),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,alpha = 0.5) + ##稍后添加到OP
plot_list [[i]] = p
}
#将地块保存到tiff。为每个绘图创建一个单独的文件。
for(i in 1:3){
file_name = paste(iris_plot_,i,.tiff,sep =)
tiff(file_name)
print (plot_list [[i]])
dev.off()
}
我缺少什么?
< img src =https://i.stack.imgur.com/6oL9N.pngalt =在这里输入图片描述>
for循环
中的数据集,所以同样的图形重复三次而不变。 b $ b
请注意这里的变化:
plot_list = list()
for我在唯一(虹膜$物种)){
p = ggplot(iris [iris $ Species == i,],aes(x = Sepal.Length,y = Sepal.Width))+
geom_point( size = 3,aes(color = Species))
plot_list [[i]] = p
}
填充< - iris%>%
解决OP更新问题,这对我有用:
dist inct(Species,.keep_all = TRUE)
for(i in unique(iris $ Species)){
p = ggplot(iris [iris $ Species == i,],aes(x =数据=填充,aes(填充= Petal.Width),xmin = -Inf,xmax = Inf,ymin = -Inf,ymax = Inf,= Sepal.Length,y = Sepal.Width))+
geom_rect alpha = 0.5)+
geom_point(size = 3,aes(color = Species))
plot_list [[i]] = p
}
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?
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
}
这篇关于在ggplot2中的循环问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!