0

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))
}
akano
  • 15
  • 4

1 Answers1

0

Simply add a filter inside your loop to build a plot on current looped 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))
}

Alternatively, use base R's by and avoid the explicit for loop and unique() call:

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))
})
Parfait
  • 104,375
  • 17
  • 94
  • 125