Reputation: 43
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:
recent_quarter <- c(12, 15, 2, 3)
all_data <- c(218, 323, 34, 12)
recent_perc <- c(38,47,6,9)
all_perc <- c(37,55,4,5)
gender <- factor(c("M", "F", "Unknown", "Other"),
levels = c("M", "F", "Unknown", "Other"))
df <- data.frame(gender, all_data, recent_quarter, all_perc,
recent_perc, all_data)
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.
Upvotes: 0
Views: 1558
Reputation: 226047
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)
Upvotes: 1
Reputation: 321
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)
Upvotes: 0