Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading