在R中标记x轴

时间:2017-07-13 04:43:27

标签: r plot

 Month <- as.yearmon("2013-02") + 0:37/12
 plot(Month, H, type = "l", col="blue", ylim=c(5, 7), ylab="")
 lines(Month,Z, type = "l", col = "red", ylim=c(5, 7))
 legend("topright",legend=c(expression(Forcasted), expression(Acutal),
   col = c('blue', 'red'),
   lty = 1:1)

我的数据从2013年2月开始到2016年3月。我只想在&#34; x轴&#34;从2013年2月开始到2016年3月结束的月份和年份。我尝试了多项但没有一项工作。 plot ( output of the above code)

1 个答案:

答案 0 :(得分:1)

df = ts(rnorm(50), frequency = 12, start = 2001)
plot(df, xaxt = "n")
tsp = attributes(df)$tsp
dates = seq(as.Date("2015-01-01"), by = "month", along = df)
axis(1, at = seq(tsp[1], tsp[2], along = df), labels = format(dates, "%m-%Y")) 

> df = data.frame(date = seq(as.POSIXct("2014-01-01"), by = "month", length.out = 50), pcp = rnorm(50))
    > library(ggplot2)
    > library(scales)
    > p = ggplot(data = df, aes(x = date, y = pcp)) + geom_line()
    > p + scale_x_datetime(labels = date_format("%m-%Y"), breaks = date_breaks("months")) + theme(axis.text.x = element_text(angle = 90))