Home > Software engineering >  Creating facets for ggplot boxplots
Creating facets for ggplot boxplots

Time:11-25

I have a dataframe set up as follows:

Region Sub-region March April May
A A1 9.2 7.9 8.0
A A2 8.9 8.5 8.0
A A3 9.5 8.5 8.4
B B1 9.1 8.7 8.5
B B2 9.9 8.0 7.7
C C1 8.7 8.0 8.2
C C2 9.3 8.0 8.4
C C3 9.1 8.3 8.5

I've melted the dataframe so its in this format:

Region Sub-region Variable Value

I'm trying to create a ggplot boxplot with a facet wrap/grid so that the output contains a panel for each region and within each panel is a boxplot for each sub-region. I've tried the below code but it's not the desired output:

p<- Name_SR %>% 
  ggplot(aes(value, sub_region))   
  geom_boxplot()   
  labs(title="",
       subtitle ="
         ",
       x="Percentage Difference", 
       y = "Sub-Region")   
  facet_wrap(~Region)  
  theme(panel.grid = element_blank(),
        plot.margin=unit(c(1,6,1,1),"cm"),
        plot.title = element_text(size=12), 
        plot.subtitle = element_text(size=10),
        axis.title = element_text(size = 10))
q<- p   theme(axis.text = element_text(size=8))

Would someone be able to help me please?

CodePudding user response:

I think this should do what you are looking for, if Name_SR is your melted df...

Name_SR %>% 
  ggplot(aes(x = sub_region, y = value))    #yours are the wrong way round
  geom_boxplot()  
  facet_wrap(~Region, scales = "free_x")    #free_x removes irrelevant subregions
  • Related