首页 文章

当x轴是日期时使用abline()(即时间序列数据)

提问于
浏览
7

我想在绘图中添加多条垂直线 .

通常你会指定 abline(v=x-intercept) 但我的x轴是Jan-95 - Dec-09的形式 . 我如何调整abline代码以添加垂直线,例如在95年2月?

我已经尝试了 abline(v=as.Date("Jan-95")) 和这段代码的其他变种 .

接下来是可以用一段代码添加多条垂直线,例如95年2月,97年2月和98年1月?


另一种解决方案可能是改变我的情节,我有一个包含月份信息的列和一个包含年份信息的列,我如何协作这些以在X轴上有一年的月份?

example[25:30,]
   Year Month    YRM TBC
25 1997     1 Jan-97 136
26 1997     2 Feb-97 157
27 1997     3 Mar-97 163
28 1997     4 Apr-97 152
29 1997     5 May-97 151
30 1997     6 Jun-97 170

2 回答

  • 3

    第一个注意事项:您的YRM列可能是一个因素,而不是日期时间对象,除非您手动转换它 . 我认为我们不想这样做,我们的情节看起来很好,因为YRM是一个因素 .

    在这种情况下

    vline_month <- function(s) abline(v=which(s==levels(df$YRM)))
    # keep original order of levels
    df$YRM <- factor(df$YRM, levels=unique(df$YRM))
    plot(df$YRM, df$TBC)
    vline_month(c("Jan-97", "Apr-97"))
    

    enter image description here

    免责声明:这个解决方案是一个快速的黑客攻击;它既不普遍也不可扩展 . 要准确表示日期时间对象及其可扩展工具,请参阅包 zooxts .

  • 5

    我看到两个问题:

    a)将您的数据转换为日期/ POSIX元素,和

    b)实际绘制特定行的垂直线 .

    首先,创建一个正确的日期字符串,然后使用 strptime() .

    通过使用 as.numeric() 将POSIX日期转换为数字来解决第二个问题 .

    # dates need Y-M-D
    example$ymd <- paste(example$Year, '-', example$Month, '-01', sep='')
    
    # convet to POSIX date
    example$ymdPX <- strptime(example$ymd, format='%Y-%m-%d')
    # may want to define tz otherwise system tz is used
    
    # plot your data
    plot(example$ymdPX, example$TBC, type='b')
    
    # add vertical lines at first and last record
    abline(v=as.numeric(example$ymdPX[1]), lwd=2, col='red')
    abline(v=as.numeric(example$ymdPX[nrow(example)]), lwd=2, col='red')
    

    Simple plot with dates on x-axis and vertical lines creating using abline

相关问题