Home > Mobile >  Add brackets over a bar plot of factor variable (geom_bar, geom_bracket)
Add brackets over a bar plot of factor variable (geom_bar, geom_bracket)

Time:10-05

I am trying to use geom_bracket to annotate a bar plot of ordered categorical bars.

Example data and plot:

df <- tibble(
  country= c("ENG","ESP", "ITA", "FRA", "NLD", "POR", "AUT", "TUR", "CHE", "RUS"),
  share=c(25.71, 21.74, 11.54, 10.49,  3.76,  3.73,  2.67,  2.34,  2.07,  1.97)
) 

df %>% 
  ggplot()  
  geom_bar(aes(x = reorder(country, -share), y = share), stat = "identity", width = 0.8, position = "dodge") 

Plot

I played around with geom_bracket to group bars together (e.g. first four (ENG to FRA) as "Top 4"), but couldn't get it to work, often times running into the following error message:

Error in data.frame(label = label, y.position = y.position, xmin = xmin,  : 
  arguments imply differing number of rows: 0, 1

How can i add a horizontal bracket floating above the bars (at y=30)?

CodePudding user response:

To achieve your desired result you could create a data frame containing the numeric xmin and xmax positions where you want to draw your brackets and the label. Additionally you have to pass the y position of the brackets via y.position:

library(ggplot2)
library(ggpubr)

ggplot(df)  
  geom_col(aes(x = reorder(country, -share), y = share), width = 0.8, position = "dodge")  
  geom_bracket(
    aes(xmin = xmin, xmax = xmax, label = label),
    data = data.frame(xmin = c(1, 7), xmax = c(4, 10), label = c("Top 4", "Bottom 4")), y.position = c(30, 5)
  )

CodePudding user response:

Try this:

ggplot(df, aes(x = reorder(country, -share), y = share))  
  geom_bar(stat = "identity", width = 0.8, position = "dodge")  
  #add bracket
  geom_bracket(xmin = 1, xmax = 4,
               y.position = max(df$share) * 1.05,
               label = "Top 4")  
  #extend y-axis to show text on bracket
  ylim(0, max(df$share) * 1.1)

enter image description here

  • Related