添加具有独特颜色和尺寸的自定义Axis标签

时间:2020-07-21 01:17:05

标签: r

我有以下图表:

df<- data.frame(year=c(1960,1961,1962),value=c(10,18,20))
ggplot(df,aes(x=year,y=value))+geom_col()+
geom_hline(yintercept =18,linetype="dashed", color = "red",size=1)

enter image description here

我想在Y轴上添加一个红色标签,其中红线位于文本“实际值”处。

我知道我无法添加文本更改符,但后来我无法将新文本更改为红色。

有什么方法可以只更改一个人的颜色和大小,而不能更改轴上的其他图例?

我正在寻找这样的东西:

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用geom_text

library(ggplot2)

ggplot(df,aes(x=year,y=value))+geom_col()+
  geom_hline(yintercept =18,linetype="dashed", color = "red",size=1) +
  geom_text(aes(1960,18,label = 'Actual Value', vjust = -1),
           color = 'red', size = 8)

enter image description here

答案 1 :(得分:1)

这里是annoate的一种方法:

  1. 使用annoate指定要绘制的文本。提供x = y = 参数以指示要绘制的位置。
  2. 使用coord_cartesianclip = 'off'在绘图区域之外进行绘图,并使用xlim = 将x轴固定到数据上,而不是包括annotate调用的坐标
  3. 使用plot.margin扩大左边距,以便为文本留出空间。

您可能需要修改xlimx = 参数以使其正确使用。

ggplot(df,aes(x=year,y=value)) + 
  geom_col() +
  geom_hline(yintercept =18,linetype="dashed", color = "red",size=1) + 
  coord_cartesian(clip = 'off',
                  xlim = c(1959.5,1962.5)) +
  annotate(geom = "text", y = 18, x = 1959.1, color = "red", label = "Actual Value") +
  theme(plot.margin = unit(c(1,1,1,3), "lines"))

enter image description here

修改: 您可以在标签中使用\n,使文本显示在两行中。

ggplot(df,aes(x=year,y=value)) + 
  geom_col() +
  geom_hline(yintercept =18,linetype="dashed", color = "red",size=1) + 
  coord_cartesian(clip = 'off',
                  xlim = c(1959.5,1962.5)) +
  annotate(geom = "text", y = 18, x = 1959.2, color = "red", label = "Actual\nValue") +
  theme(plot.margin = unit(c(1,1,1,2), "lines"))

enter image description here