在 R 中绘制具有不连续轴的时间序列
plot time series with discontinuous axis in R
我想画一个时间序列,把中间的一段时间去掉。如果我单独绘制系列,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轴上获取日期,但不显示排除日期的空白区域?
三种选择:
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。 plotrixAnother 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")
我想我明白了。按照我上面提出的思路,我不得不用 axis
命令 fiddle 很长时间才能让它把日期标签放在正确的位置。这是我使用的:
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 的观点,它看起来很有误导性。也许如果我在中断处放一条垂直虚线...
我想画一个时间序列,把中间的一段时间去掉。如果我单独绘制系列,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轴上获取日期,但不显示排除日期的空白区域?
三种选择:
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。 plotrixAnother 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")
我想我明白了。按照我上面提出的思路,我不得不用 axis
命令 fiddle 很长时间才能让它把日期标签放在正确的位置。这是我使用的:
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 的观点,它看起来很有误导性。也许如果我在中断处放一条垂直虚线...