Changing background color for a text annotation to

2020-08-10 09:30发布

问题:

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

回答1:

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



回答2:

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