gpt4 book ai didi

r - 时间序列中的日期与 X 轴不对齐

转载 作者:行者123 更新时间:2023-12-02 04:44:28 24 4
gpt4 key购买 nike

我正在尝试绘制从 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")))

enter image description here请注意,我的 x 轴是荷兰语。您将使用您自己的语言,但您可以通过更改 Sys.setlocale 来更改它。

关于r - 时间序列中的日期与 X 轴不对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34374580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com