[英]Date in Time Series Does not Line up with X-axis
我試圖從2015年4月7日開始到2015年11月23日結束,以15分鍾的間隔從水流中收集水溫。 我想讓x軸在每個刻度標記處標記為“Apr”,“May”等,直到“Nov”。 我寫的代碼看起來很漂亮,但溫度讀數與x軸刻度標記不對齊; 它們始於2015年4月1日,與2015年4月7日相反; 因此,所有的溫度讀數都要比它們應該移動7天。 換句話說我希望x軸在4月1日開始,但是數據從它們被收集的日期開始。我認為它與我如何對時間進行排序和應用刻度有關,但我不確定如何糾正它。 任何幫助將不勝感激。 謝謝
#Load Data
trib<-read.csv("C:\\r.data\\trib.csv",header=TRUE)
#Index Time
trib$DateTime<-as.POSIXct(strptime(trib$DateTime,"%m/%d/%Y %H:%M"))
#Create Time Series
trib.xts<-xts(trib,order.by=trib$DateTime)
#Example Data
DateTime Temp
22666 2015-04-07 13:30:00 NA
22667 2015-04-07 13:45:00 2.983
22668 2015-04-07 14:00:00 3.142
22669 2015-04-07 14:15:00 3.274
22670 2015-04-07 14:30:00 3.354
22671 2015-04-07 14:45:00 3.433
22672 2015-04-07 15:00:00 3.485
22673 2015-04-07 15:15:00 3.670
22674 2015-04-07 15:30:00 3.749
22675 2015-04-07 15:45:00 3.827
#Plot
par(mfrow=c(1,1))
margins <- par(mar=c(2,2,1,1)+0.1)
omargins <- par(oma=c(2,2,0.5,0.5)+0.1)
Temp.lab=seq(0,30,by=5)
Temp.ticks=seq(0,30,by=5)
plot(trib.xts$Temp,axes=FALSE,auto.grid=FALSE,col="gray",ylim=c(0,30),main="Stream Name",cex.main=0.8,lwd=1)
axis(2,at=Temp.ticks,labels=format(Temp.lab,scientific=FALSE),ylab="Temperature (C)",las=1,cex.axis=0.8)
times <- time(trib.xts$DateTime["2015-04-01/2015-11-15"])
ticksm <- seq(times[1], times[length(times)], by = "months")
month.lab = c("Apr","May","Jun","Jul","Aug","Sep","Oct","Nov")
axis(1, at = ticksm, labels = month.lab, tcl = -0.5,cex.axis=0.8,xlab="Month")
mtext("Temperature (°C)",side=2,line=3,las=3,cex=0.8)
mtext("Month",side=1,line=3,cex=0.8)
假設您不介意ggplot解決方案,這是一種方法。
# Let's first make SampleData to your specifications:
trib.xts <- data.frame(DateTime = seq.POSIXt(as.POSIXct("2015/04/07 13:30:00",Format="%Y/%m/%d %H:%M:%S", timezone ="CEST"),
as.POSIXct("2015/11/23 13:00:00",Format="%Y/%m/%d %H:%M:%S", timezone ="CEST"),
by="15 min"))
# Then add temperature, a bit warmer in summer.
trib.xts$Temp <- 2*sin(month(trib.xts$DateTime))+rnorm(22083,mean=7,sd=2)
#Now, we need ggplot and scales
library(ggplot2)
library(scales)
#then make a plot
(plot1 <- ggplot(trib.xts, aes(x=DateTime, y=Temp)) +
geom_point(col="gray",shape=1) +
theme_bw(24) +
ggtitle("Stream Name") +
ylab("Temperature (°C)") +
xlab("Month"))
# Now set the breaks, labels and x-limits as you please
(plot1 <- plot1 +
scale_x_datetime(breaks = "1 month",
labels=date_format("%b"),
limits = as.POSIXct(c("2015-03-30","2015-11-25"), timezone="CEST")))
請注意,我的x軸是荷蘭語。 您將使用自己的語言,但可以通過更改
Sys.setlocale
來更改此Sys.setlocale
。
謝謝,RHA。 我按照你的建議在月初(例如4/1/2015 00:00,NA)添加了錯誤的溫度讀數。 這似乎是用我創建的x軸刻度標記“排列”數據。 是時候熟悉ggplot了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.