Home > Enterprise >  ggplot two side by side graphs with the same scale
ggplot two side by side graphs with the same scale

Time:10-04

I'm trying to create two side by side graphs to compare the values (one absolute values and one proportions). I managed to create some simple graphs, but I cannot figure out if I have to wrap them or use a grid? I just keep getting errors.

My data looks something like this:

Then I created a simple plot

ggplot(df, aes(x = gender, y = recent_perc))  
  geom_col(fill = "gray70")  
  theme_minimal() 

For this one, I'd like to add a second plot with the all_perc as the y axis. I'm stumped on how to do this.

CodePudding user response:

You could:

g1 <- ggplot(df, aes(x = gender, y = recent_perc))  
  geom_col(fill = "gray70")  
  theme_minimal() 
g2 <- g1   aes(y=all_perc)
cowplot::plot_grid(g1,g2)

gridExtra (as referenced in @Josh's answer) and patchwork are two other ways to do the grid assembly.

Or:

library(tidyverse)
df <- data.frame(gender, all_data, recent_quarter, all_perc, all_data, recent_perc)
df_long <- df %>% 
    select(gender, ends_with("perc")) %>% 
    pivot_longer(-gender) ## creates 'name', 'value' columns
ggplot(df_long, aes(gender, value))   geom_col()  
   facet_wrap(~name)

CodePudding user response:

install the package gridExtra and use:

grid.arrange(
ggplot(df, aes(x = gender, y = recent_perc))  
  geom_col(fill = "gray70")  
  theme_minimal(), 
ggplot(df, aes(x = gender, y = all_perc))  
  geom_col(fill = "gray70")  
  theme_minimal(), 
ncol = 2)
  • Related