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