I am trying to use a loop to create and save individual charts by an ID number. I'm not sure if I am doing the loop wrong, or if it is related to the data setup. The plot I end up with has data for both IDs plotted on it, but is saved twice based on the names defined by the ggsave command. I feel like I'm missing something simple.
The data I'm using is like this:
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))
And this is my code:
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))
}