0

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
  • 401
  • 6
  • 23

2 Answers2

2

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
  • 377,200
  • 20
  • 156
  • 213
  • 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
2

You can use

aes(get(col,df),..count..))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81