ggplot for loop outputs all the same graph

前端 未结 1 1907
悲哀的现实
悲哀的现实 2020-12-11 23:17

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 t

相关标签:
1条回答
  • 2020-12-11 23:47

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

    Now, about your plots.

    Best solution

    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)
    

    Otherwise…

    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)
    

    0 讨论(0)
提交回复
热议问题