Justine Oesterle Justine Oesterle - 1 month ago 4
R Question

geom_bar x and y values do not match on plot

I have a list of dataframes that I am trying to make bar plots from using a for loop.

This is the list if data frames

test2<- list(WBq2, WSq2, Kq2, Nq2, Fq2, LHq2, Lynq2, Mq2, NEq2, WB2q2, MCq2, Cq2, M2q2, NE2q2, K2q2, N2q2, MC2q2, C2q2, F2q2, LH2q2, GPq2 )


Each data frame looks like this- K2q2.

date market Question Responses
9 31-Jul K2 $0 4
10 31-Jul K2 $1-10 26
11 31-Jul K2 $11-25 88
12 31-Jul K2 $26-50 43
13 31-Jul K2 $51-100 11
14 31-Jul K2 $100+ 2


This is the vector of names I am using

names2 <- c('WestBroadway', "West Side", "Kingfield","Nokomis", "Fulton", "Linden Hills", "Lyndale", "Midtown", "Northeast", "West Broadway2", "Mill City", "Camden", "Midtown2", "Northeast2", "Kingfield2", "Nokomis2", "Mill City2", "Camden2", "Fulton2", "Linden Hills2", "Govenors Plaza" )


This is my for loop:

for (i in test2){
for (j in names2){
i$Question <- factor(i$Question, levels = i$Question)
plot <- ggplot(data = i, aes(x = Question, y = Responses)) +
geom_bar(stat="identity") +
ggtitle(j) +
labs(x="How much did you spend or plan on spending at the market today?", y= "Responses")
ggsave(filename=paste(j,"Q22",".pdf",sep=""), plot=plot, device = "pdf")
}
}


The problem I am having is when I run this loop the plots are produced by the x labels (Question) do not match to the y labels (Response). How do you you get these two values to stick together like they are in the K2q2 dataframe?

Thanks!

Answer

Without a reproducible example it may be difficult to make a solution. Try this, if it works that's great, if it doesn't I'll remove it.

j = 1 #initialize counter
for (i in test2){

  i$Question <- factor(i$Question, levels = i$Question)
  plot <- ggplot(data = i, aes(x = Question, y = Responses)) + 
    geom_bar(stat="identity") + 
    ggtitle(names2[j]) + 
    labs(x="How much did you spend or plan on spending at the market today?", y= "Responses") 
  ggsave(filename=paste(names2[j], "Q22", ".pdf", sep=""), 
         plot=plot, device = "pdf")

j = j + 1 #update counter

}