【发布时间】:2019-03-18 20:13:35
【问题描述】:
我正在尝试使用循环通过 ID 号创建和保存单个图表。我不确定我是否做错了循环,或者它是否与数据设置有关。我最终得到的图上绘制了两个 ID 的数据,但根据 ggsave 命令定义的名称保存了两次。我觉得我错过了一些简单的东西。
我使用的数据是这样的:
df <- data.frame(ID = c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2),
Time = c("1","2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2"),
Category = c("Red", "Red", "Red", "Red", "Blue", "Blue", "Blue", "Blue", "Yellow","Yellow", "Yellow", "Yellow"),
Score = c(0, 0, 0, 0, 1, 2, 0, 3, 1, 1, 3, 2))
这是我的代码:
idlist <-unique(df$ID)
for (i in idlist) {
plot<- df %>%
ggplot(aes(x=Category, y=as.numeric(Score), fill=Time))+
geom_bar(color="black", stat="identity", position=position_dodge(.8), width=0.75)+
geom_text(aes(x=Category, y=Score,label=Score), position=position_dodge(width=1), hjust=0.5, vjust=-.25, size=3)+
labs(x="Category",y="Score")
ggsave(filename=paste("plot",id[i],".png",sep=""), plot,
device = function(...) png(..., units="in",res=200))
}
【问题讨论】:
-
您实际上并没有按 id 过滤任何内容。所有图表都将完全相同。
-
为此:
id[i],你在哪里定义了id?