Tam HN
Tam HN

Reputation: 33

How to make combined bar plots by iterating through factor variables?

I find my code inefficient and want to make it faster by iterating through factor variables in the dataset and use plot_grid() to combine these plots together. But I don't know how.

Here is the repetitive code I write a lot of times.

`3` <- customer_personal_profiles %>% 
  ggplot(aes(Education)) +
  geom_bar() +
  coord_flip() +
  theme_bw()

`2` <-customer_personal_profiles %>% 
  ggplot(aes(EmploymentStatus)) +
  geom_bar() +
  coord_flip() +
  theme_bw()

`1` <- customer_personal_profiles %>% 
  ggplot(aes(Gender)) +
  geom_bar() +
  coord_flip() +
  theme_bw()

cowplot::plot_grid(`1`, `2`, `3`)

The code produced this graph:

enter image description here

I found the code quite lengthy and repetitive. Is there any way I can make it in several lines of code?

Thank you!

Upvotes: 1

Views: 32

Answers (3)

Tam HN
Tam HN

Reputation: 33

Thank you all. I also realized I can use gather to shorten the code:

customer_profiles_baked %>%
  select_if(is.factor) %>% 
  gather(x, y, Education:Location.Code) %>% 
  count(x, y) %>% 
  ggplot(aes(x = y, y = n)) +
  facet_wrap(~ x, ncol = 2, nrow = 3, scales = "free") +
  geom_segment( aes(xend=y, yend=0 )) +
  geom_point( size=2, color="chocolate4", alpha = 0.6)  +
  coord_flip() +
  theme_bw() +
  ylab("Count") +
  xlab("Personal Profile Variables")

This results in:

enter image description here

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

We could get all the variables to plot in a variable and loop over them using lapply/map, convert the characters to symbol and evaluate them and store the plots in a list. We can now use this list to plot using plot_grid. Using reproducible example from mtcars.

vals <- c("carb", "gear", "cyl")
library(ggplot2)

group_plot <- lapply(vals, function(x) ggplot(mtcars, aes(!!rlang::sym(x))) +
                                       geom_bar() +
                                       coord_flip() +
                                       theme_bw())

cowplot::plot_grid(plotlist = group_plot)

enter image description here


So for your case, you could do

vals <- c("Gender", "EmploymentStatus", "Education")
group_plot <- lapply(vals, function(x) ggplot(customer_personal_profiles, 
                                       aes(!!rlang::sym(x))) +
                                       geom_bar() +
                                       coord_flip() +
                                       theme_bw())

cowplot::plot_grid(plotlist = group_plot)

Upvotes: 1

dww
dww

Reputation: 31452

Using mtcars data to make this reproducible:

g = ggplot(mtcars) +
  geom_bar() +
  coord_flip() +
  theme_bw()

a = g + aes(cyl)  
b = g + aes(mpg)   
cowplot::plot_grid(a,b)

enter image description here

Upvotes: 0

Related Questions