简体   繁体   English

在R中使用自定义标签绘制X轴

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

I've to plot these data: 我必须绘制这些数据:

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

in the x-axis I want to label only the month and the day (eg Jan 02 ). 在x轴上,我只想标记月份和日期(例如Jan 02)。 How can I do this using the command plot() and axis() ? 如何使用plot()axis()命令执行此操作?

First, you will need to put your date text into a dtae class (eg as.POSIXct ): 首先,您需要将日期文本放入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")

Your dates should now plot correctly. 您的日期现在应该可以正确绘制了。 Don't apply the x-axis, by using the argument xaxt="n" . 不要通过使用参数xaxt="n"来应用x轴。 Afterwards, you can create a sequence of dates where you would like your axis labeled, and apply this with axis.POSIXct : 之后,您可以创建一个日期序列,在该序列中您希望将轴标记为标签,然后将其与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")

在此处输入图片说明

Similarly, to get a daily axis, simply modify the SEQ and axis.POSIXct code accordingly. 同样,要获取每日坐标轴,只需相应地修改SEQaxis.POSIXct代码。 For example, you may try: 例如,您可以尝试:

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