我有一个数据帧列表,我试图通过使用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 $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
这是我正在使用的名字的载体
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标签(Response)不匹配。你如何将这两个值粘在一起,就像它们在K2q2数据帧中一样?
谢谢!
答案 0 :(得分:0)
如果没有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
}