Home > Enterprise >  Ggplot - always place 'Total' bar as the farthest right bar using geom_col
Ggplot - always place 'Total' bar as the farthest right bar using geom_col

Time:03-09

I am creating a chart that looks like the below. Problem is that I'd like the grey 'total' bar to always be on the far right hand side.

enter image description here

Current code is below, can anyone please amend/provide any additional code to create this effect?

#plot with reorder
PrevalencePlot <- ggplot(ICSTable4, aes(x = reorder(value, Area), y = value, fill = Statistical_Significance))  
  geom_col()    
  scale_fill_manual(values = colours) 
    geom_errorbar(aes(ymin=errorbarlowerplot, ymax=errorbarhigherplot),
                width=.2,                    # Width of the error bars
                position=position_dodge(.9))  
  theme_bw()   
  geom_text(aes(label = valuelabel), vjust = 2.5, colour = "black") 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))

If anyone is able to help then the below data frame could be used to generate the principle I think? Thank you!

df <- data.frame(Area = c("Area1", "Area2", "Area3", "Area4", "Total"),
                 Value = c(1, 3, 7, 5, 4)
)

CodePudding user response:

Building on the minimal example data, we can make a spartanic version of the plot that addresses the question of ordering the values, and placing a selected column at the end.

df <- data.frame(Area = c("Area1", "Area2", "Area3", "Area4", "Total"),
                 value = c(1, 3, 7, 5, 4),
                 Statistical_Significance = c("higher", "lower", "lower", "higher", NA))

It's easier to create the order of the columns before plotting, as we need to create the factors based on the order of value and then reposition the target column ("Total").

df <- df %>% 
  dplyr::arrange(desc(value)) %>% #arrange by value
  dplyr::mutate(Area = forcats::as_factor(Area)) %>% # factor that defines order on x-axis
  dplyr::mutate(Area = forcats::fct_relevel(Area, "Total", after = Inf)) # reposition "Total" column


ggplot(df, aes(x = Area, y = value, fill = Statistical_Significance))  
  geom_col()    
  theme_bw() 

enter image description here

  • Related