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

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

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

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