Home > Enterprise >  Obtain two barplots in the same graph ggplot2
Obtain two barplots in the same graph ggplot2

Time:01-20

I have two dataframes:

df1 <- data.frame(name = rep(LETTERS[1:5], each = 5), age = 1:25)
df2 <- data.frame(name = rep(LETTERS[1:5], each = 5), age = c(rep(1,5), rep(5,5), 1,12,3,2,1,1:5,6:10))

And I want to produce horizontal barplots like these:

df1 %>%
  mutate(name = fct_reorder(name, age)) %>%
  ggplot( aes(x = name, y = age))  
  geom_bar(stat = "identity", fill = "#74D055FF", alpha = .6, width = .6)  
  coord_flip()  
  theme_bw()

df2 %>%
  mutate(name = fct_reorder(name, age)) %>%
  ggplot( aes(x = name, y = age))  
  geom_bar(stat = "identity", fill = "#481568FF", alpha = .6, width = .6)  
  coord_flip()  
  theme_bw()

I would like to show them in the same figure: there should be a vertical line in correspondence of age = 0, and then the violet bars should go on one side and the green ones on the other (of course it will then be sorted only based on age of either df1 or df2, as the descending order of age is not the same in both dataframes). I don't know how this type of plot it's called and how to approach this.

CodePudding user response:

One option would be to bind your datasets into one dataframe and add an identifier column for which I use dplyr::bind_rows. The identifier could then be mapped on the fill aes and the colors set via scale_fill_manual. Also I aggregated the data using count instead of relying on stacking:

library(dplyr)
library(ggplot2)

dplyr::bind_rows(df1, df2, .id = "id") %>%
  count(id, name, wt = age, name = "age") |>
  mutate(
    name = reorder(name, (id == 1) * age, sum),
    age = if_else(id == 2, -age, age)
  ) |>
  ggplot(aes(y = name, x = age, fill = id, group = 1))  
  geom_col(alpha = .6, width = .6)  
  geom_vline(xintercept = 0)  
  scale_fill_manual(values = c("#74D055FF", "#481568FF"))  
  theme_bw()

enter image description here

  • Related