簡體   English   中英

在R中使用自定義標簽繪制X軸

[英]plotting x-axes with custom label in R

我必須繪制這些數據:

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()命令執行此操作?

首先,您需要將日期文本放入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")

您的日期現在應該可以正確繪制了。 不要通過使用參數xaxt="n"來應用x軸。 之后,您可以創建一個日期序列,在該序列中您希望將軸標記為標簽,然后將其與axis.POSIXct一起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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM