1

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

This makes a graph like this: enter image description here

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?

Michael
  • 35
  • 1
  • 6

1 Answers1

1

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)

Update:

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)
M--
  • 25,431
  • 8
  • 61
  • 93
  • Thanks Masound. This works as is, but it would be nice if there was a solution that could: 1) scale for different sizes of plots (the y axis won't always be at a max of three) and 2) automatically draw the legend box. I guess annotate can draw shapes as well, but the same issue exists here when plot sizes are different. – Michael Jun 22 '17 at 23:16
  • Read this [thread](https://stackoverflow.com/questions/7705345/how-can-i-extract-plot-axes-ranges-for-a-ggplot2-object). You can get the y and x lim from ggplot and then set the x and y in annotate to them. – M-- Jun 23 '17 at 04:03