我试图从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)
答案 0 :(得分:0)
这是一种方法,假设你不介意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")))
来更改此选项