2

我必须绘制这些数据:

day        temperature
02/01/2012 13:30:00 10 
10/01/2012 20:30:00 8
15/01/2012 13:30:00 12
25/01/2012 20:30:00 6
02/02/2012 13:30:00 5
10/02/2012 20:30:00 3
15/02/2012 13:30:00 6
25/02/2012 20:30:00 -1
02/03/2012 13:30:00 4
10/03/2012 20:30:00 -2
15/03/2012 13:30:00 7
25/03/2012 20:30:00 1

在 x 轴上,我只想标记月份和日期(例如 Jan 02 )。如何使用命令plot()和来做到这一点axis()

4

1 回答 1

1

首先,您需要将日期文本放入 dtae 类(例如as.POSIXct):

df <- structure(list(day = structure(list(sec = c(0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0), min = c(30L, 30L, 30L, 30L, 30L, 30L, 30L, 
30L, 30L, 30L, 30L, 30L), hour = c(13L, 20L, 13L, 20L, 13L, 20L, 
13L, 20L, 13L, 20L, 13L, 20L), mday = c(2L, 10L, 15L, 25L, 2L, 
10L, 15L, 25L, 2L, 10L, 15L, 25L), mon = c(0L, 0L, 0L, 0L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L), year = c(112L, 112L, 112L, 112L, 
112L, 112L, 112L, 112L, 112L, 112L, 112L, 112L), wday = c(1L, 
2L, 0L, 3L, 4L, 5L, 3L, 6L, 5L, 6L, 4L, 0L), yday = c(1L, 9L, 
14L, 24L, 32L, 40L, 45L, 55L, 61L, 69L, 74L, 84L), isdst = c(0L, 
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L)), .Names = c("sec", 
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst"
), class = c("POSIXlt", "POSIXt")), temperature = c(10L, 8L, 
12L, 6L, 5L, 3L, 6L, -1L, 4L, -2L, 7L, 1L)), .Names = c("day", 
"temperature"), row.names = c(NA, -12L), class = "data.frame")

df
df$day <- as.POSIXct(df$day, format="%d/%m/%Y %H:%M:%S")

您的日期现在应该正确绘制。不要通过使用参数来应用 x 轴xaxt="n"。之后,您可以创建一个日期序列,您希望您的轴标记,并应用它axis.POSIXct

plot(df$day, df$temperature, t="l", ylab="Temperature", xlab="Date", xaxt="n")
SEQ <- seq(min(df$day), max(df$day), by="months")
axis.POSIXct(SEQ, at=SEQ, side=1, format="%b %Y")

在此处输入图像描述

同样,要获得每日轴,只需相应地修改SEQaxis.POSIXct代码。例如,您可以尝试:

plot(df$day, df$temperature, t="l", ylab="Temperature", xlab="Date", xaxt="n")
SEQ <- seq(min(df$day), max(df$day), by="days")
axis.POSIXct(SEQ, at=SEQ, side=1, format="%b %d")
于 2013-04-29T12:59:08.643 回答