ggplot2 - annotate - 更改文本注释的背景颜色

时间:2016-09-20 20:00:57

标签: ggplot2 background-color annotate

我想更改注释文本的背景颜色,使其为绿色并覆盖其背后的任何内容(如下例中的水平线)。我该怎么做?

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

enter image description here

2 个答案:

答案 0 :(得分:17)

请尝试geom_label

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

答案 1 :(得分:0)

this answer为基础,但避免使用geom_label(),以便标签仅绘制一次,而不是为绘制的数据的每一行绘制一次(如this comment中正确指出的那样):

您仍然可以使用annotate(),这是一次性注释的首选方法,但是使用label代替text作为geom

同样,您可以提供geom="segment"来画一条线,等等...

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

plot