当x轴的格式为`%Y-%m-%d%H:%M:%S`时,如何使用anateate()在ggplot2中添加字母?

问题描述 投票:-1回答:1

我有下一个情节:

enter image description here

获得它的代码是这样:

Plot<- ggplot(foo,aes(x=Time, y=value, colour=Axis)) + 
  geom_line(size=1) +
  theme_bw() + 
  labs(x=expression(Time~(HMS)),y=expression(Raw~acceleration~(g))) + 
  theme(strip.background=element_blank(),
        axis.title.x =element_text(margin = margin(t = 10, r = 0, b = 0, l = 0),size = 16,face = "bold"),
        axis.title.y =element_text(margin = margin(t = 0, r = 10, b = 0, l = 0),size = 16,face = "bold"),
        axis.text.x = element_text(angle = 0, hjust = 0.5,size = 15),
        axis.text.y = element_text(angle = 0, hjust = 0.5,size = 15),
        axis.line = element_line(),
        panel.grid.major= element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=14),
        legend.title = element_text(size=15, face = "bold"),
        legend.key=element_blank(),
        legend.position = "right",
        panel.border = element_blank(),
        strip.placement = "outside") +
  guides(color=guide_legend(override.aes=list(fill=NA))) +
  scale_x_datetime(labels = date_format("%H:%M:%S"),
    breaks=date_breaks("10 sec")) +
  scale_y_continuous(breaks = seq(-4,3,1))
Plot

我正在尝试使用annotate()在图中添加字母,但是由于x轴的格式为%Y-%m-%d %H:%M:%S,所以我不知道如何获得它。

Plot  + annotate("text", x=as.POSIXct("15:40:00"), y=-3.5, label= "A")
Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

有人知道怎么做吗?

提前感谢

r ggplot2 annotate
1个回答
0
投票

我找到了路。我刚刚在x位置创建了一个想要字母的对象。例如,就我而言,我希望这封信在15:40:05左右,所以我这样做了:

Time1 <- foo$Time[foo$Time>"2020-03-21 16:40:05.000" & foo$Time<"2020-03-21 16:40:05.100" & foo$Axis=="surge"]

一旦有了这个,我只需要参考Time1中的annotate()

Plot  + annotate("text", x=Time1, y=-3.5, label= "A")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.