简体   繁体   中英

How to plot sunrise over a year in R?

I have date that looks like this:

"date", "sunrise"
2009-01-01, 05:31
2009-01-02, 05:31
2009-01-03, 05:33
2009-01-05, 05:34
....
2009-12-31, 05:29

and I want to plot this in R, with "date" as the x-axis, and "sunrise" as the y-axis.

You need to work a bit harder to get R to draw a suitable plot (ie get suitable axes). Say I have data similar to yours (here in a csv file for convenience:

"date","sunrise"
2009-01-01,05:31
2009-01-02,05:31
2009-01-03,05:33
2009-01-05,05:34
2009-01-06,05:35
2009-01-07,05:36
2009-01-08,05:37
2009-01-09,05:38
2009-01-10,05:39
2009-01-11,05:40
2009-01-12,05:40
2009-01-13,05:41

We can read the data in and format it appropriately so R knows the special nature of the data. The read.csv() call includes argument colClasses so R doesn't convert the dates/times into factors.

dat <- read.csv("foo.txt", colClasses = "character")
## Now convert the imported data to appropriate types
dat <- within(dat, {
date <- as.Date(date) ## no need for 'format' argument as data in correct format
sunrise <- as.POSIXct(sunrise, format = "%H:%M")
})
str(dat)

Now comes the slightly tricky bit as R gets the axes wrong (or perhaps better to say they aren't what we want) if you just do

plot(sunrise ~ date, data = dat)
## or
with(dat, plot(date, sunrise))

The first version gets both axes wrong, and the second can dispatch correctly on the dates so gets the x-axis correct, but the y-axis labels are not right.

So, suppress the plotting of the axes, and then add them yourself using axis.FOO functions where FOO is Date or POSIXct :

plot(sunrise ~ date, data = dat, axes = FALSE)
with(dat, axis.POSIXct(x = sunrise, side = 2, format = "%H:%M"))
with(dat, axis.Date(x = date, side = 1))
box() ## complete the plot frame

HTH

I think you can use the as.Date and as.POSIXct functions to convert the two columns in the proper format (the format parameter of as.POSIXct should be set to "%H:%M" )

The standard plot function should then be able to deal with time and dates by itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM