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 total number to ggplot legend

I made a frequency barplot with the following data and code:

structure(list(Geslacht = c("man", "man", "man", "man", "man", 
"man", "man", "vrouw", "vrouw", "vrouw", "vrouw", "vrouw", "vrouw", 
"vrouw", "vrouw"), Lengteklasse = c(6, 7, 8, 9, 10, 11, 12, 6, 
7, 8, 9, 10, 11, 12, 13), Freq = c(1L, 9L, 19L, 21L, 35L, 22L, 
5L, 2L, 13L, 19L, 37L, 45L, 40L, 6L, 1L)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -15L), groups = structure(list(
    Geslacht = c("man", "vrouw"), .rows = structure(list(1:7, 
        8:15), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))
ggplot(Freq_lengteklasse, aes(Lengteklasse, Freq, fill = Geslacht))+
  geom_col()+
  scale_x_continuous(breaks = seq(6,13, by = 1))+
  scale_y_continuous(breaks = seq(0,80, by = 10))+
  labs(x = "Lengteklasse (cm)", y = "Frequentie")+
  scale_fill_manual(values=c('lightgray','black'))+
  theme_classic()

I want to add the total count of man and vrouw which should say n = 275, positioned under the legend. How would one do this?

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

>Solution :

You can add a tag in your labs which will display the total number. You can change the position of the tag in the theme with plot.tag.position. You can use the following code:

library(tidyverse)
ggplot(Freq_lengteklasse, aes(Lengteklasse, Freq, fill = Geslacht))+
  geom_col()+
  scale_x_continuous(breaks = seq(6,13, by = 1))+
  scale_y_continuous(breaks = seq(0,80, by = 10))+
  labs(x = "Lengteklasse (cm)", y = "Frequentie", tag = paste('n =', sum(Freq_lengteklasse$Freq)))+
  scale_fill_manual(values=c('lightgray','black'))+
  theme_classic() +
  theme(plot.tag.position = c(0.95, 0.4))

Output:

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