gpt4 book ai didi

r - ggplot 的时间轴

转载 作者:行者123 更新时间:2023-12-05 04:00:39 25 4
gpt4 key购买 nike

我有一个时间序列(每小时)数据,我想打印该数据的选定时间段。假设我想打印从 2019 年 1 月 1 日 00:00 到 2019 年 1 月 8 日 00:00 的一周数据。我希望刻度线从 2019 年 1 月 1 日的 00:00 开始。但出于我不知道的原因,ggplot 从 03:00 开始。我错过了什么吗?

这里是复制问题的示例代码:

library(ggplot2)
library(scales)
Sys.setenv( TZ = "GMT" )

datetime <- seq(from = as.POSIXct("2019-01-01", tz = "GMT"), length.out = 744, by = "hours")
random<- rnorm(744,100,20)

df <- data.frame(datetime,random)

time.start=as.POSIXct("2019-01-01 00:00",format="%Y-%m-%d %H:%M")
time.end=as.POSIXct("2019-01-08 00:00",format="%Y-%m-%d %H:%M")

png(filename = "test_ggplot.png", width = 800, height = 600, units = "px", pointsize = 24 )
plot.random = ggplot() +
geom_line(data=df, aes(x=datetime, y=random)) +
scale_x_datetime(limits = c(time.start,time.end),
breaks = date_breaks("12 hours"),
labels = date_format("%H:%M\n%d-%b")
)
plot.random

这是图表,显示 x 轴刻度标记标签从 03:00 而不是 00:00 开始。

example ggplot time axis problem

最佳答案

我希望您的限制输入有效,这可能是一个错误。如果我删除 limits 参数并添加 expand 它似乎会做你想做的事:

ggplot() +
geom_line(data = df %>% head(300), aes(x = datetime, y = random)) +
scale_x_datetime(
#limits = c(time.start, time.end),
breaks = date_breaks("12 hours"),
labels = date_format("%H:%M %d-%b"),
expand = expand_scale(0)
) +
theme(axis.text = element_text(angle = 90))

enter image description here

关于r - ggplot 的时间轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56042086/

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