geom_bar x 和 y 值在图上不匹配

geom_bar x and y values do not match on plot

我有一个数据框列表,我正在尝试使用 for 循环制作条形图。

如果数据帧

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

每个数据框看起来像这样- K2q2。

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

这是我正在使用的名称向量

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" )

这是我的 for 循环:

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")
  }
} 

我遇到的问题是,当我 运行 这个循环时,x 标签(问题)生成的图与 y 标签(响应)不匹配。你如何让这两个值像在 K2q2 数据框中一样粘在一起?

谢谢!

没有 reproducible example 可能很难找到解决方案。试试这个,如果它有效,那就太好了,如果它没有,我会删除它。

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

}