-1

I want to produce bar plots for each column in a data frame.

I tried the following code to produce plot for a single column and it's working fine.

ggplot(df, aes(colName, ..count..)) + geom_bar(aes(fill = colName), position = "dodge")

But it's not working if i put it in a for loop to produce plot for each column in the data frame.

for(col in names(df)){
    print(col)
    ggplot(df, aes(col, ..count..)) + geom_bar(aes(fill = col), position = "dodge")
  }

I don't want to hard code the column names in the code and I don't want to develop a separate function.

Anne
  • 371
  • 5
  • 20

2 Answers2

2

You can use

aes(get(col,df),..count..))
ThomasIsCoding
  • 80,151
  • 7
  • 17
  • 65
1

You can create plots for each column of your dataframe using lapply. To refer to column name as variable in ggplot code use .data :

library(ggplot2)

lapply(names(df), function(col) {
  ggplot(df, aes(.data[[col]], ..count..)) + 
    geom_bar(aes(fill = .data[[col]]), position = "dodge")
}) -> list_plots
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • Thank you for the answere. But I don't want to develop a seperate function – Anne Apr 19 '21 at 09:22
  • What do you mean by 'develop a separate function'? `lapply` is same as `for` loop. You can use the same logic in `for` loop as well. What is your expected output? – Ronak Shah Apr 19 '21 at 09:24