我想绘制一个时间序列,在中间排除一段时间的情节。如果我单独绘制系列,只有x轴上的索引,那就是我得到的。内部的排除点集不会出现。
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就会尽职地呈现准确的真实时间尺度,包括排除的日期。这会在图上产生一个空白区域。
plot(Dates[dummy == 1], x[dummy == 1])
如何在x轴上获取日期,但不显示排除日期的空白区域?
答案 0 :(得分:0)
三种选择:
<强> 1。 ggplot2 显然,ggplot2
would not allow for a discontinuous axis但你可以使用facet_wrap
来获得类似的效果。
# 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")
<强> 2。基础R
plot(df$x ~ df$Dates, col= ifelse( df$f=="A", "blue", "red"), data=subset(df, dummy==1))
第3。 plotrix Another alternative would be to use gap.plot{plotrix}
。代码将如下所示。但是,我无法弄清楚如何在具有date
值的轴上休息。也许这会是另外一个问题。
library(plotrix)
gap.plot(Dates[dummy == 1], x[dummy == 1], gap=c(24,35), gap.axis="x")
答案 1 :(得分:0)
我想我明白了。按照我上面提出的方法,我不得不长时间使用axis
命令来将日期标签放在正确的位置。这是我使用的:
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认为它看起来很误导。也许如果我在休息时放一条垂直的虚线......