ggplot for循环输出所有相同的图 [英] ggplot for loop outputs all the same graph

查看:167
本文介绍了ggplot for循环输出所有相同的图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个for循环,该循环遍历数据帧的各列,并使用ggplot为每一列生成一个图形.问题在于输出的图都是一样的-它们都是最后一列的图.

I've written a for loop which goes through the columns of a dataframe and produces a graph for each column using ggplot. The problem is the graphs that are output are all the same - they're all graphs of the final column.

我使用的代码是:

library(gridExtra)
library(ggplot2)
test1 <- c("Person1","Person2","Person3","Person4","Person5")
test2 <- as.data.frame(c(1,2,3,4,5))
test3 <- as.data.frame(c(2,2,2,2,2))
test4 <- as.data.frame(c(1,3,5,3,1))
test5 <- as.data.frame(c(5,4,3,2,1))
test <- cbind(test1,test2,test3,test4,test5)
rm(test1,test2,test3,test4,test5)
colnames(test) <- c("Person","var1","var2","var3","var4")

for(i in 2:5){
  nam <- paste0("graph", i-1)
  graph_temp <- ggplot(test, aes(Person, test[,i])) + geom_bar(stat = "identity")
  assign(nam, graph_temp)
}
grid.arrange(graph1, graph2, graph3, graph4, ncol=2)

我的目标是这段代码中的情节:

What I'm aiming for is the plot from this code:

library(gridExtra)
library(ggplot2)
test1 <- c("Person1","Person2","Person3","Person4","Person5")
test2 <- as.data.frame(c(1,2,3,4,5))
test3 <- as.data.frame(c(2,2,2,2,2))
test4 <- as.data.frame(c(1,3,5,3,1))
test5 <- as.data.frame(c(5,4,3,2,1))
test <- cbind(test1,test2,test3,test4,test5)
rm(test1,test2,test3,test4,test5)
colnames(test) <- c("Person","var1","var2","var3","var4")

graph1 <- ggplot(test, aes(Person, test[,2])) + geom_bar(stat = "identity")
graph2 <- ggplot(test, aes(Person, test[,3])) + geom_bar(stat = "identity")
graph3 <- ggplot(test, aes(Person, test[,4])) + geom_bar(stat = "identity")
graph4 <- ggplot(test, aes(Person, test[,5])) + geom_bar(stat = "identity")
grid.arrange(graph1, graph2, graph3, graph4, ncol=2)

我知道在保存ggplots时有一个类似的问题在for循环中,但是我没有设法让那个解决这个问题.

I know there's a similar question on saving ggplots in a for loop, but I've not managed to get that one to work for this problem.

推荐答案

以下是生成示例的更简洁方法:

Here's a more concise way to produce your example:

df <- data.frame(
  Person = paste0("Person", 1:5),
  var1 = c(1,2,3,4,5),
  var2 = c(2,2,2,2,2),
  var3 = c(1,3,5,3,1),
  var4 = c(5,4,3,2,1)
)

现在,关于您的地块.

将数据框重塑为长"格式,然后使用构面:

Reshape the data frame to 'long' format, and then use facets:

library(ggplot2)
library(tidyr)
gather(df, var, value, -Person) %>%
  ggplot(aes(Person, value)) +
    geom_bar(stat = "identity") +
    facet_wrap(~ var)

如果您要坚持看起来像您发布的数据结构,请使用 aes_string :

If you gotta stick with a data structure that looks like what you posted, then use aes_string:

library(ggplot2)
library(gridExtra)

g <- lapply(1:4, function(i) {

  ggplot(df, aes_string("Person", paste0("var", i))) +
    geom_bar(stat = "identity")

})
grid.arrange(grobs = g, ncol = 2)

这篇关于ggplot for循环输出所有相同的图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆