关于日期:在R中具有不连续轴的时间序列图

plot time series with discontinuous axis in R

我想绘制一个时间序列,在图中不包括中间的一段时间。 如果我只绘制系列,而在x轴上只有一个索引,那就是我得到的。 内部排除点集不会出现。

1
2
3
4
x <- rnorm(50)
Dates <- seq(as.Date("2008-1-1"), by ="day", length.out = length(x))
dummy <- c(rep(1, 25), rep(0, 10), rep(1, length(x) - 35))
plot(x[dummy == 1])

但是,一旦日期在x轴上,R就会忠实地提供准确的真实时间标度,包括排除的日期。 这将在图上产生空白区域。

1
plot(Dates[dummy == 1], x[dummy == 1])

如何在x轴上获取日期,但不显示排除日期的空白区域?


我想我知道了。 按照上面的建议,我不得不花很长时间使用axis命令来使它将日期标签放置在正确的位置。 这是我使用的:

1
2
3
plot(x[dummy == 1], xaxt ="n", xlab ="")  # plot with no x-axis title or tick labels
Dates1_index <- seq(1,length(Dates1), by = 5)  # set the tick positions
axis(1, at = Dates1_index, labels = format(Dates1[Dates1_index],"%b %d"), las = 2)

成功之后,我现在同意@alistaire的观点,这似乎很容易引起误解。 也许如果我在断点处画一条垂直虚线...


三种选择:

1. ggplot2显然,ggplot2不允许轴不连续,但是您可以使用facet_wrap获得类似的效果。

1
2
3
4
5
6
7
8
9
10
11
12
# get the data
  x = rnorm(50)
  df <- data.frame( x = x,
                  Dates = seq(as.Date("2008-1-1"), by ="day", length.out = length(x)) ,
                  dummy = c(rep(1, 25), rep(0, 10), rep(1, length(x) - 35)))

  df$f <- ifelse(df$Dates <="2008-01-25",  c("A"), c("B"))

# plot
  ggplot( subset(df, dummy==1)) +
    geom_point(aes(x= Dates, y=x)) +
    facet_wrap(~f , scales ="free_x")

enter image description here

2.基数R

1
plot(df$x ~ df$Dates, col= ifelse( df$f=="A","blue","red"), data=subset(df, dummy==1))

enter image description here

3. plotrix另一个替代方法是使用gap.plot{plotrix}。 代码如下。 但是,我不知道如何在具有date值的轴上断开。 也许这将是另外一个问题。

1
2
3
library(plotrix)

gap.plot(Dates[dummy == 1], x[dummy == 1], gap=c(24,35), gap.axis="x")