2

I am using a character vector that contains the the variables in my data frame I want to graph using ggplot. I am setting the x variable using a for loop, but ggplot does not seem to be assigning the variable correctly.

My data frame (data) has a number of factor variables I want to plot using geom_bar. I created a character vector (chars) which contains the column names of the factor variables. I'm having difficulties with my loop assigning the desired variables.

chars <- c("school", "address", "famsize", "Pstatus", "Mjob", "Fjob", "reason", "guardian", "schoolsup", "famsup", "paid", "activities", "nursery", "higher", "internet", "romantic")

data[chars] <- lapply(data[chars], factor)

for (i in chars) {
   print(ggplot(data, aes(x = i))) +
     geom_bar()
}

I was hoping that I would end up with a bar plot of all the variables, but instead, I am getting a series of blank plots that are titled as each object in chars . What am I doing wrong?

Che Diaz
  • 55
  • 5
  • 2
    This sounds like you neet to convert your data into long format. can you supply the dataframe by pasting the output of `dput(data)`? also, maybe have a look at this question regarding reshaping your data: https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format – f.lechleitner Apr 10 '19 at 05:33

1 Answers1

2

You might be able to use aes_string instead of aes:

print(ggplot(data, aes_string(i)) + geom_bar())
olorcain
  • 1,230
  • 1
  • 9
  • 12