在r中编辑日期轴

时间:2017-07-05 20:51:41

标签: r date plot ggplot2 axis

我正在使用时间线,由于某种原因,我最终会得到一个或多或少随机的时间尺度。我们走了:

df <- data.frame(balance=c(100,242,156,430,224),
  date = as.Date(c("2017-01-03", "2017-01-14", "2017-02-03", "2017-02-17", "2017-03-02")))

我将以下内容绘制:

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date", 
                                 yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, df$date, format(df$date, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

我得到的是:

enter image description here

如何控制日期轴?而不是Jan 03, Jan 14, Feb 03, Feb 17, Mar 02我希望Jan 01, Jan 15, Feb 01, Feb 15, Mar 01

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

您需要将这些特定日期提供给axis函数;这对你有用:

date_lab <- 
           as.Date(c("2017-01-01", "2017-01-15", "2017-02-01", "2017-02-15", "2017-03-01"))

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date", 
                             yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, date_lab, format(date_lab, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

enter image description here

如果您使用ggplot2,通常会使轴比基座plot更清晰:

library(ggplot2)
ggplot(df, aes(x=date, y=balance))+geom_line()+
                                   labs(title = "Personal finance",
                                        x = "Date", y="Balance [$]")

enter image description here