Home > Software design >  Plotting a bar chart with multiple groups
Plotting a bar chart with multiple groups

Time:12-04

I have a dataframe group by treatment status and by a categorical variable df %>% group_by(treatment, categorical_var) %>% summarise(n=n()) and I am trying to get a similar bar plot as the one shown in picture using ggplot in which my y axis would be determined by my $n$ variable and my x axis would be determined by my $categorical_var$

enter image description here

As shown in the picture I am basically trying to merge two bar charts in the same plot one for the control group and the other for the treatment group. Any help on how to do this?

Here is a reproducible example


example <- tribble(
  ~treatment, ~categorical_var, ~n,
  "control",            "1",    10,
  "control",            "2",    12,
  "control",            "3",     7,
  "treatment",          "1",     14,
  "treatment",          "2",     5,
  "treatment",          "3",     11,
)


ggplot(example, aes(categorical_var, n))   
  geom_bar(position="dodge",stat="identity")   facet_wrap(~treatment)

And here is the putput I get, how can I change the style to get something like the picture from above?

enter image description here

CodePudding user response:

Styling always involves a bit of fiddling and trial (and sometimes error (;). But generally you could probably get quite close to your desired result like so:

library(ggplot2)

ggplot(example, aes(categorical_var, n))   
  geom_bar(position="dodge",stat="identity")   
  # Add some more space between groups
  scale_x_discrete(expand = expansion(add = .9))  
  # Make axis start at zero
  scale_y_continuous(expand = expansion(mult = c(0, .05)))  
  # Put facet label to bottom 
  facet_wrap(~treatment, strip.position = "bottom")  
  theme_minimal()  
  # Styling via various theme options
  theme(panel.spacing.x = unit(0, "pt"), 
        strip.placement = "outside", 
        strip.background.x = element_blank(),
        axis.line.x = element_line(size = .1),
        panel.grid.major.y = element_line(linetype = "dotted"),
        panel.grid.major.x = element_blank(),
        panel.grid.minor = element_blank())

  • Related