用R中的不连续轴绘制时间序列 [英] plot time series with discontinuous axis in R

查看:309
本文介绍了用R中的不连续轴绘制时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  x<-rnorm(50)
日期<-seq(as.Date( 2008-1 -1),by = day,length.out = length(x))
虚拟<-c(rep(1,25),rep(0,10),rep(1,length( x)-35))
图(x [dummy == 1])$ ​​b $ b

一次日期在x轴上,但是,R忠实地提供了准确的真实时间标度,包括排除的日期。

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

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

解决方案

三种选择:



1。 ggplot2 显然, ggplot2



2。基本R

 图(df $ x〜df $ Dates,col = ifelse(df $ f == A, blue, red),data = subset(df,dummy == 1))



3。 plotrix 另一种选择是使用 gap.plot {plotrix } 。代码如下。但是,我不知道如何在具有 date 值的轴上进行中断。

  library(plotrix)

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


I want to plot a time series, excluding in the plot a stretch of time in the middle. If I plot the series alone, with only an index on the x-axis, that is what I get. The interior set of excluded points do not appear.

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])

Once the dates are on the x-axis, however, R dutifully presents an accurate true time scale, including the excluded dates. This produces a blank region on the plot.

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

How can I get dates on the x-axis, but not show the blank region of the excluded dates?

解决方案

Three alternatives:

1. ggplot2 Apparently, ggplot2 would not allow for a discontinuous axis but you could use facet_wrap to get a similar effect.

# 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. base 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}. The code would be something like this one below. However, I couldn't figure out how to make a break in an axis with date values. Perhaps this would and additional question.

library(plotrix)

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

这篇关于用R中的不连续轴绘制时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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