28

I'd like to change the background color for my annotate text so that it's green and covers up anything behind it (like the horizontal line in the example below). How do I do that?

ggplot() + 
  geom_hline(yintercept=0) + 
  annotate("text",x=0,y=0,label="Here is a line")

enter image description here

Henrik
  • 65,555
  • 14
  • 143
  • 159
Andy Stein
  • 461
  • 1
  • 4
  • 11
  • 1
    You can use `annotate("rect",xmin=?,xmax=?, ymin=?, ymax=?, fill="yellow")` and you should use this line before the "text annotate", however `geom_label` is a lot cleaner – Ibo Apr 18 '18 at 23:57

2 Answers2

45

Try geom_label instead:

ggplot() + 
  geom_hline(yintercept = 0) + 
  labs(x = "", y = "") +
  geom_label(aes(x = 0, y = 0, label = "Here is a line"), fill = "green")

enter image description here

Martin Schmelzer
  • 23,283
  • 6
  • 73
  • 98
  • 3
    NOTE that `geom_label` must be mentioned after `geom_hline` otherwise the line will be visible over the label – Ibo Apr 18 '18 at 23:58
  • 3
    Note that in``annotate(geom = "label", x = 0, y =0, color = "red", fill = "green")``, the ``color`` argument will apply to both the text and the box line around it (as far as I can tell). – PatrickT Nov 27 '18 at 12:17
  • 3
    For anyone using geom_label, note the performance hit as it draws for every row. https://github.com/tidyverse/ggplot2/issues/2266. Found this out the hard way as all my plotting ground to a halt – sam Mar 08 '19 at 14:22
23

Building on this answer, but avoiding the use of geom_label() so that the label draws only once, not once for every row of plotted data (as correctly pointed out in this comment):

You can still use annotate(), which is the preferred approach for a one-off annotation, but use label instead of text as the geom.

Likewise you could supply geom="segment" to draw a line, etc...

ggplot() + 
  geom_hline(yintercept=0) + 
  annotate(geom="label",x=0,y=0,label="Here is a line", fill="green")

plot

mac
  • 3,137
  • 1
  • 28
  • 42
  • 16
    I would like to add to this good answer that ``label.size = NA`` removes those black fill borders: ``annotate(geom="label",x=0,y=0,label="Here is a line",label.size=NA,fill="green")``. Thanks to: https://stackoverflow.com/a/45376078/9455395 – Vesanen May 23 '20 at 16:25