geom_vline + geom_text:垂直旋转标签时对齐标签

时间:2019-11-08 07:17:51

标签: r ggplot2

我正在用ggplot进行绘制,并在x截距上放置一些垂直标签,如下所示:

d=data.frame(date=as.Date(c("1971-09-01", "1991-12-01", "1994-12-01", "2000-01-01", "2002-08-01")),
             event=c(2.6, 14.1, 30.3, 60.5, 91.3))
ggplot() +
  scale_x_date(limits=as.Date(c("1970-1-1", "2010-12-31"))) +
  scale_y_continuous(name="", breaks=NULL, limits=c(0,1)) +
  geom_vline(data=d, mapping=aes(xintercept=date), color="blue") +
  geom_text(data=d, mapping=aes(x=date, y=0, label=event), 
            size=4, angle=270, vjust=-0.4, hjust=7)

我的图表是这样的:

enter image description here

如何将第一个x截距上的数字2.6与其他x截距对齐?

2 个答案:

答案 0 :(得分:0)

也许将 y 设置在中间(0.5而不是0),而不使用 just

ggplot(d, aes(x = date, y = 0.5, label = event)) +
  geom_text(size = 4, angle = 270, vjust = -0.7) +
  geom_vline(mapping = aes(xintercept = date), color = "blue") +
  scale_x_date(limits = as.Date(c("1970-1-1", "2010-12-31"))) +
  scale_y_continuous(name = "", breaks = NULL, limits = c(0, 1))

enter image description here

答案 1 :(得分:0)

对于水平方向(旋转90度),角度只是错误

  geom_text(data=d, mapping=aes(x=date, y=0, label=event), 
        size=4, angle=90, vjust=-1, hjust=-1.1)

或在另一侧垂直放置(旋转270度)

  geom_text(data=d, mapping=aes(x=date, y=0, label=event), 
        size=4, angle=270, vjust=-1, hjust=1.1)