在X&之间创建一个图Y基于Z的背景图块着色

时间:2017-03-18 22:59:59

标签: ggplot2

嗨我有一个有三列的数据

  1. 日期
  2. 关闭(数字)
  3. 状态(1,2,3整数值)
  4. 我想根据状态绘制具有不同颜色阴影区域的关闭与日期图表。

    代码

    Price<-data.frame(y,NTRI$NTRI.Close[15:nrow(NTRI),],HMMpost[,1])
    colnames(Price) <- c( "Date","Close", "State")
    xstart<- as.Date(Price$Date[[1]])
    xend<- as.Date(Price$Date[[nrow(Price)]])
    rects<- data.frame(xstart= xstart, xend= xend, col= letters[1:3])
    
    ggplot() + 
        geom_line(data = Price, aes(x = Date, y = Close)) + 
        geom_rect(data = rects, 
                  aes(xmin = xstart, xmax = xend, 
                      ymin = 0, ymax = +Inf, fill = col), 
                  alpha = 0.5)
    

    数据

    structure(list(Close = c(22.89, 23.51, 23.45, 24.72, 26.76, 27.74, 28.62, 26.9, 30.58, 28.79, 27.25, 27.44, 23.79, 24.26, 23.33, 25.26, 24.89, 23.11, 23.89), Date = structure(c(13901, 13902, 13903, 13906, 13907, 13908, 13909, 13910, 13913, 13914, 13915, 13916, 13917, 13920, 13921, 13922, 13923, 13924, 13928), class = "Date"), State = c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3)), class = "data.frame", row.names = c(NA, -19L))
    

1 个答案:

答案 0 :(得分:0)

ggplot(data = Price, aes(x = Date, y = Close)) +
    geom_rect(aes(ymin = 0, ymax = Inf,
                  xmin = Date, xmax = lead(Date), 
                  fill = as.factor(State)), alpha =0.5) + 
    geom_line() +
    geom_point()

1