在 R 中使用 geom_rect 进行时间序列着色 [英] Using geom_rect for time series shading in R

查看:27
本文介绍了在 R 中使用 geom_rect 进行时间序列着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对时间序列图的某个部分进行着色(有点像衰退着色 - 类似于 这篇关于 excel 中的衰退阴影的文章).我放了一些可能很笨拙的示例来说明.我首先创建一个时间序列,用 ggplot2 绘制它,然后想使用 geom_rect 来提供阴影.但我的论点肯定有问题.

I am trying to shade a certain section of a time series plot (a bit like recession shading - similarly to the graph at the bottom of this article on recession shading in excel). I have put a little, possibly clumsy, sample together to illustrate. I first create a time series, plot it with ggplot2 and then want to use geom_rect to provide the shading. But I must get something wrong in the arguments.

a<-rnorm(300)
a_ts<-ts(a, start=c(1910, 1), frequency=12)
a_time<-time(a_ts)
a_series<-ts.union(big=a_ts, month=a_time)
a_series_df<-as.data.frame(a_series)
ggplot(a_series)+
  geom_line(mapping=aes_string(x="month", y="big"))+
  geom_rect(
    fill="red",alpha=0.5, 
    mapping=aes_string(x="month", y="big"), 
    xmin=as.numeric(as.Date(c("1924-01-01"))),
    xmax=as.numeric(as.Date(c("1928-12-31"))),
    ymin=0,
    ymax=2
    )

请注意,我也尝试过,但也没有用.

Note that I have also tried which also did not work.

geom_rect(
        fill="red",alpha=0.5, 
        mapping=aes_string(x="month", y="big"), 
        aes(
           xmin=as.numeric(as.Date(c("1924-01-01"))),
           xmax=as.numeric(as.Date(c("1928-12-31"))),
           ymin=0,
           ymax=2)
        )

推荐答案

代码工作正常,xminxmax 需要转换为十进制日期,见下文,需要润滑包.

Code works fine, conversion to decimal date is needed for xmin and xmax, see below, requires lubridate package.

library("lubridate")
library("ggplot2")

ggplot(a_series_df)+
  geom_line(mapping = aes_string(x = "month", y = "big")) +
  geom_rect(
    fill = "red", alpha = 0.5, 
    mapping = aes_string(x = "month", y = "big"), 
    xmin = decimal_date(as.Date(c("1924-01-01"))),
    xmax = decimal_date(as.Date(c("1928-12-31"))),
    ymin = 0,
    ymax = 2
  )

更清晰的版本,首先绘制阴影,因此线条颜色不会改变.

Cleaner version, shading plotted first so the line colour doesn't change.

ggplot() +
  geom_rect(data = data.frame(xmin = decimal_date(as.Date(c("1924-01-01"))),
                              xmax = decimal_date(as.Date(c("1928-12-31"))),
                              ymin = -Inf,
                              ymax = Inf),
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            fill = "grey", alpha = 0.5) +
  geom_line(data = a_series_df,aes(month, big), colour = "blue") +
  theme_classic()

这篇关于在 R 中使用 geom_rect 进行时间序列着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆