rggplot2legendmanual

adding a simple legend that includes a chosen text using ggplot


let's say I have this simple df with its plot as follows :

df = data.frame(a = c('person1','person2','person3'),
                b = c(10,20,30))



ggplot(df)+aes(x=a,y=b,fill=b)+
  geom_bar(stat='identity')

the outcome

enter image description here

I wish that the legend is a box that only includes (for example) the following phrase : TOTAL = 60

Thanks a lot.


Solution

  • You could create an annotation with a label. Make sure to create some space by changing the plot.margin and clip off the coords. You can play with the settings. Here is a reproducible example:

    library(ggplot2)
    ggplot(df)+aes(x=a,y=b,fill=b)+
      geom_bar(stat='identity') +
      coord_cartesian(clip = "off") +
      annotate("label", x = Inf, y = 20, hjust = -0.1, label = "TOTAL = 60", size = 3) +
      theme(plot.margin = unit(c(1,5,1,1), "lines"),
            legend.position = 'none') 
    

    Created on 2022-12-12 with reprex v2.0.2


    You could use richtext when loading ggtext to rotate an annotated box like this:

    library(ggplot2)
    library(ggtext)
    ggplot(df)+aes(x=a,y=b,fill=b)+
      geom_bar(stat='identity') +
      coord_cartesian(clip = "off") +
      annotate("richtext", x = Inf, y = 20, vjust = 2, label = "TOTAL = 60", size = 3, angle = 90) +
      theme(plot.margin = unit(c(1,5,1,1), "lines"),
            legend.position = 'none') 
    

    Created on 2022-12-12 with reprex v2.0.2