user18632888
user18632888

Reputation: 39

grouped barplot with overlapping bars in ggplot

I have the following grouped barplot for 4 different groups created with ggplot:

enter image description here

what I would like is to plot one group with a wider bar and put the other three groups as thin bars in front of the wider bar. Something like that: enter image description here

(sorry for the not matching colours)

Any ideas how to create this using ggplot?

The code for the original plot is:

cols4 <- c("#565656", "#0065c4", "#f03b20", "#73c400")
rhoc_plot <- ggplot(Table_for_Plot, aes(x = marker,
                           y = rho_c,
                           fill = cohort))+
  geom_bar(stat = "identity",
           width = 0.6,
           position = position_dodge(0.6))+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank())+
  scale_y_continuous(expand = c(0,0.0001))+
  ylab("rho c")+
  scale_fill_manual(values = cols4)

Thank you in advance!

Upvotes: 0

Views: 208

Answers (1)

stefan
stefan

Reputation: 125338

Basically you could achive your desired result using two geom_col and probably separate datasets, e..g one dataset containing the "totals" or values for the background bars per x category and a second dataset containing the values for the other three groups.

As you provided no example data I use mtcars to show this approach:

library(dplyr)
library(ggplot2)

df_am_cyl <- mtcars |> 
  count(am, cyl)

df_am <- mtcars |> 
  count(am)

cols4 <- c("#565656", "#0065c4", "#f03b20", "#73c400")

ggplot(mapping = aes(x = am, y = n))+
  geom_col(aes(fill = "0"), data = df_am, width = .75) +
  geom_col(aes(fill = factor(cyl)),data = df_am_cyl, 
           width = 0.2, position = position_dodge(0.6))+
  theme_classic()+
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank())+
  scale_y_continuous(expand = c(0,0.0001))+
  ylab("rho c")+
  scale_fill_manual(values = cols4)

Upvotes: 0

Related Questions