我是那种坚持的for loop
在ggplot2
。
我正在尝试通过ggplot2中的for循环为每个绘图标题以及文件名添加Species
和categ
名称。不知何故,该循环似乎仅以一个物种名称为标题。
library(dplyr)
data_iris <- iris%>%
mutate(categ=ifelse(Petal.Width<0.4,"A",ifelse(Petal.Width>=0.4&Petal.Width<=1.0, "B","C")))
> head(data_iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species categ
1 5.1 3.5 1.4 0.2 setosa A
2 4.9 3.0 1.4 0.2 setosa A
3 4.7 3.2 1.3 0.2 setosa A
4 4.6 3.1 1.5 0.2 setosa A
5 5.0 3.6 1.4 0.2 setosa A
6 5.4 3.9 1.7 0.4 setosa B
情节部分
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
p = ggplot(data_iris[data_iris$categ==j,], aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(size=3, aes(colour=categ))+
labs(title=paste( i,j, "species_categ",sep="_")) #this part is not working!!!
plot_list[[j]] = p
}
}
# Save plots to tiff. Makes a separate file for each plot.
library(ggplot2)
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
file_name = paste(i,j, "iris_plot_", ".tiff", sep="_")
tiff(file_name)
print(plot_list[[j]])
dev.off()
}
}
ant的输出是这样的(我没有添加所有图和名称。但是您会在工作目录中看到它们)
因此,正如我们所看到的,问题出在这里,我无法获得Species
每个图的正确名称。我不明白吗?为什么会这样呢?
试试这个。您的索引错误。首先,我可能会以不同的方式存储图-可能在列表列表中。
ind <- 1 # initialise the index for storing
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
p <- ggplot(data_iris[data_iris$categ==j,], aes(x=Sepal.Length, y=Sepal.Width)) +
geom_point(size=3, aes(colour=categ))+
labs(title=paste( i,j, "species_categ",sep="_"))
plot_list[[ind]] <- p # stor the plot
ind <- ind + 1 # increment
}
}
ind <- 1
for (i in unique(data_iris$Species)) {
for (j in unique(data_iris$categ)) {
file_name = paste(i,j, "iris_plot_", ".tiff", sep="_")
tiff(file_name)
print(plot_list[[ind]]) # use the same index to retrieve the plot
ind <- ind + 1
dev.off()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句