【发布时间】:2018-05-17 00:54:08
【问题描述】:
我有点卡在ggplot2 中的for loop。
我正在尝试通过 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()
}
}
输出是这样的(我没有添加所有的图和名称。但是你会在工作目录中看到它们)
所以,正如我们所见,问题出在此处,我无法为每个地块获得正确的 Species 名称。我无法得到它?为什么会这样?
【问题讨论】:
-
在
plot_list[[j]]中,您没有考虑i,因此您最终只会得到一个值为i的图,之前的图将被覆盖。您也根本没有在绘图循环中根据i过滤数据,我不确定您希望用它做什么。 -
@Marius 你的意思是我也应该为
Species设置过滤器?怎么样? -
我无法真正回答这个问题,因为我不知道您的目标是什么 - 如果您实际上不需要更改,您可能根本不需要
for (i in unique(data_iris$Species))外循环循环内的数据基于i。 -
@Marius 我最终想要实现的是,对于每个
Species绘制categ的子类别,并将Species和categ名称放在标题和输出中文件。这清楚吗?