我正在尝试使用循环通过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))
}
答案 0 :(得分:0)
只需在循环中添加filter
即可在当前循环的ID上构建图:
idlist <-unique(df$ID)
for (i in idlist) {
plot <- df %>%
filter(ID == i) %>%
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", i, ".png", sep=""), plot,
device = function(...) png(..., units="in", res=200))
}
或者,使用基数R的by
并避免显式的for
循环和unique()
调用:
by(df, df$ID, function(sub) {
plot <- ggplot(sub, 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=paste0("plot", sub$id[[1]], ".png"), plot,
device = function(...) png(..., units="in", res=200))
})