How to combine two geom_col on the same axis

I am trying to combine two plots into one but on the same axis, not next to each other (no facet wrap). The issue with the data I have is there is overlap between two categories of data, ideally I could just gather them but that wouldn't work unless I made a third category which doesn't fit with the project I am doing.

Referencing this solution, I did the following

library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.0.3
#> Warning: package 'readr' was built under R version 4.0.3
library(ggplot2)
df<-
tibble::tribble(
               ~cohort1.1,       ~cohort2.1,  ~decreased_lvef,
  "Yes", "No",  "Yes",
  "Yes", "No", "No",
  "Yes", "Yes",  "Yes",
  "Yes", "No",  "No",
  )
one<-
  df %>%
  filter(cohort1.1 == "Yes") %>%
  group_by(cohort1.1,decreased_lvef) %>%
  count()
two<-
  df %>%
  filter(cohort2.1 == "Yes") %>%
  group_by(cohort2.1,decreased_lvef) %>%
  count()
one %>%
  ggplot() +
  geom_col(mapping = aes(x = cohort1.1, y = n, fill = decreased_lvef)) +
  geom_col(data = two, mapping = aes(x = cohort2.1, y = n, fill = decreased_lvef))

Which doesn't put each column next to the other on the same axis.

Is this the graph you are looking for?

library(ggplot2)
library(dplyr, warn.conflicts = FALSE)
library(tibble)
library(tidyr)
df<-
  tibble::tribble(
    ~cohort1.1,       ~cohort2.1,  ~decreased_lvef,
    "Yes", "No",  "Yes",
    "Yes", "No", "No",
    "Yes", "Yes",  "Yes",
    "Yes", "No",  "No",
  )

pivot_longer(df,cols = c("cohort1.1","cohort2.1")) %>% 
  filter(value=="Yes") %>% 
  group_by(name,decreased_lvef) %>% 
  count() %>% 
  ggplot(aes(name,n,fill=decreased_lvef))+geom_col()

Created on 2021-03-30 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.