仅在ggplot中显示变量点标签的第一个实例

时间:2017-08-18 01:25:59

标签: r ggplot2

我有一个像这样的数据框

GROUP <- c("PRE_ANALYSIS","PRE_ANALYSIS","BEFORE","AFTER","AFTER","AFTER","AFTER","AFTER","AFTER","AFTER","AFTER")
PDATETIME <- c("2016-11-23 06:08:39","2017-02-25 15:31:50","2017-04-06 17:11:57","2017-04-15 01:23:51 CDT",
               "2017-04-16 15:54:35","2017-04-16 23:48:14","2017-04-18 02:57:41","2017-04-20 05:12:33 CDT",
               "2017-04-20 14:33:20","2017-04-22 12:33:44","2017-04-23 10:50:49")
DELTA <- c(766.3770,863.8409,893.1615,656.1001,832.9232,912.3867,934.9714,-64.7182,460.3154,949.2538,697.3750)

df <- data.frame(GROUP,PDATETIME,DELTA) 
df$PDATETIME <- as.POSIXct(df$PDATETIME,format="%Y-%m-%d %H:%M:%S")

我正在尝试创建一个新列&#34; IsChangePoint&#34;其值为

"CP Detected" for the first changepoint, the first index of df$GROUP = "AFTER"

我试图这样做

df$IsChangepoint <- ifelse(df$GROUP == "AFTER", "CP Detected", "No")

然后得到这个情节

library(ggplot2)
library(ggrepel)
ggplot(data = df, aes(PDATETIME,DELTA ))+ 
  ggtitle("Changepoint Analysis") + 
  theme(axis.text.x = element_text(angle=90, vjust=1),plot.title = element_text(size = rel(1))) + 
  geom_point(aes(colour=df$GROUP), size = 6) +
  geom_text_repel(aes(PDATETIME, DELTA, label = df$IsChangepoint)) +
  labs(colour="GROUP") + 
  xlab("PDATETIME")+ 
  ylab("DELTA")

enter image description here

这标记变更点之后的所有索引。如何绘制&#34; CP DETECTED&#34;的第一个实例?

所需的情节: enter image description here

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

看起来您希望IsChangepoint采用3个值中的1个:

  1. GROUP!=&#34; After&#34;:&#34; No&#34; (编辑基于OP的评论:这也应该是空白的)
  2. GROUP ==&#34; AFTER&#34; &安培;该组中的第1行:&#34; CP检测到&#34;
  3. GROUP ==&#34; AFTER&#34; &安培;不是这一组中的第一行:&#34;&#34; (空白)
  4. 如果是这种情况,以下内容将在数据集中为您提供:

    df <- df %>% 
      arrange(PDATETIME) %>%
      group_by(GROUP) %>% mutate(IsChangepoint = row_number() == 1) %>% ungroup() %>% 
      mutate(IsChangepoint = ifelse(GROUP == "AFTER" & IsChangepoint, "CP Detected", ""))
    

    你原来的ggplot代码对我有用,虽然我认为确实没有必要在df$电话中放geom_text_repel() ...

    ggplot(data = df, aes(PDATETIME,DELTA ))+ 
      ggtitle("Changepoint Analysis") + 
      theme(axis.text.x = element_text(angle=90, vjust=1),plot.title = element_text(size = rel(1))) + 
      geom_point(aes(colour=df$GROUP), size = 6) +
      geom_text_repel(aes(PDATETIME, DELTA, label = IsChangepoint)) +
      labs(colour="GROUP") + 
      xlab("PDATETIME")+ 
      ylab("DELTA")
    

    updated plot