简体   繁体   English

如何在R中绘制一年中的日出?

[英]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. 我想在R中以“日期”为x轴,以“日出”为y轴绘制此图。

You need to work a bit harder to get R to draw a suitable plot (ie get suitable axes). 您需要更努力地工作才能获得R来绘制合适的图形(即获得合适的轴)。 Say I have data similar to yours (here in a csv file for convenience: 假设我有与您类似的数据(为方便起见,在csv文件中:

"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. 我们可以读取数据并将其适当地格式化,因此R知道数据的特殊性质。 The read.csv() call includes argument colClasses so R doesn't convert the dates/times into factors. read.csv()调用包含参数colClasses因此R不会将日期/时间转换为因子。

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 现在稍微有些棘手,因为R弄错了轴(或者也许更好地说它们不是我们想要的),如果您这样做的话

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. 第一个版本的两个轴都错了,第二个版本的日期可以正确发送,因此x轴正确了,但是y轴的标签不正确。

So, suppress the plotting of the axes, and then add them yourself using axis.FOO functions where FOO is Date or POSIXct : 因此,抑制轴的绘制,然后使用axis.FOO函数将其自己添加,其中FOODatePOSIXct

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 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" ) 我认为您可以使用as.Dateas.POSIXct函数以正确的格式转换两列( as.POSIXctformat参数应设置为"%H:%M"

The standard plot function should then be able to deal with time and dates by itself 然后,标准plot功能应该能够自己处理时间和日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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