我有以下图表:
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)
我想在Y轴上添加一个红色标签,其中红线位于文本“实际值”处。
我知道我无法添加文本更改符,但后来我无法将新文本更改为红色。
有什么方法可以只更改一个人的颜色和大小,而不能更改轴上的其他图例?
我正在寻找这样的东西:
谢谢!
答案 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)
答案 1 :(得分:1)
这里是annoate
的一种方法:
annoate
指定要绘制的文本。提供x =
和y =
参数以指示要绘制的位置。coord_cartesian
和clip = 'off'
在绘图区域之外进行绘图,并使用xlim =
将x轴固定到数据上,而不是包括annotate
调用的坐标plot.margin
扩大左边距,以便为文本留出空间。您可能需要修改xlim
和x =
参数以使其正确使用。
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"))
修改:
您可以在标签中使用\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"))