Reputation: 35
I am trying to add a legend to a density plot generated via ggplot2, but instead of adding sample labels, I am trying to fill the legend with numbers.
library(ggplot2)
library(modeest)
set.seed(9)
d1=as.data.frame(rnorm(1000,mean=0.33,sd=0.138))
names(d1)=c("value")
mean_d1=mean(d1$value) #Mean=0.33081
mode_d1=mlv(d1$value,method="shorth")[1] #Mode=0.35191
gg=ggplot(d1,aes(value))
gg +
geom_density()
Is there a way to add a legend (embedded in the upper right corner) which contains the mean and mode values I have already calculate?
Upvotes: 1
Views: 1890
Reputation: 28955
You can add text to ggplot
using annotate
:
p + annotate("text", x = 0.6, y = 3, label = paste ("Mean ==", mean_d1), parse = TRUE) +
annotate("text", x = 0.6, y = 2.8, label = paste ("Mode ==", mode_d1), parse = TRUE)
If you want to use this for different plots then look below;
max_y <- ggplot_build(gg)$layout$panel_ranges[[1]]$y.range[2]
max_x <- ggplot_build(gg)$layout$panel_ranges[[1]]$x.range[2]
gg +
annotate("text", x = max_x * 0.85, y = max_y * 0.95, label = paste
("Mean ==", round(mean_d1, digits=3)), parse = TRUE) +
annotate("text", x = max_x * 0.85, y = max_y * 0.9, label = paste
("Mode ==", round(as.numeric(mode_d1), digits=3)), parse = TRUE)
Upvotes: 1