gpt4 book ai didi

r - ggplot2 中的小时刻度

转载 作者:行者123 更新时间:2023-12-04 08:15:53 25 4
gpt4 key购买 nike

我正在处理就寝时间和起床时间,所以我想创建一个 24 小时 x 轴的图表,从第 1 天的中午 12 点开始,到第 2 天的下午 12 点结束。这意味着在晚上 11:59 之后,它应该再次从 0 开始.
同样的问题只有数字,我想创建一个从 10 到 20 的比例,然后在 20 之后再次从 1 开始直到 10。
这是我现在拥有的代码:

ggplot(SLEEP2, aes(x=as.POSIXct(bedT, format="%H:%M"), y=Jour))+ 
geom_rect(aes(xmin=as.POSIXct(sleepT, format="%H:%M"), xmax=as.POSIXct(wakeT,
format="%H:%M"),ymin=(Jour-0.4), ymax=(Jour+0.4)),fill="orange",
color="black")+ scale_x_datetime()
我想用酒吧代表他们的 sleep 时间......
我怎样才能做到这一点?我尝试了几个选项,但没有任何效果。
谢谢你。

最佳答案

您可以使用 scales_x_...功能与自定义标签功能来实现你想要的。这是示例,由于您没有提供可重现的示例,我只是创建了自己的版本,可能并不完美,请随时检查和调整。

library(dplyr)
library(lubridate)
library(ggplot2)
df <- tibble(time = seq(from = as.POSIXct("2020-01-01 00:00:00"),
by = "1 hour", length.out = 48),
number = seq(1, by = 1, length.out = 48),
y_value = runif(48, min = 0, max = 60))

format_time_label <- function(x) {
hour(x)
}

df[["hour"]] <- day(df[["time"]]) * hour(df[["time"]])
ggplot(data = df) +
geom_bar(aes(x = time, y = y_value), stat = "identity") +
scale_x_datetime(date_breaks = "1 hour", labels = format_time_label)
enter image description here
对于这个数字,我不确定你想要什么,所以我每 20 次重新开始回到 1。
format_number_label <- function(x) {
x[x %% 20 == 0] <- 20
x[x > 20] <- x[x > 20] - (x[x > 20] %/% 20) * 20
x
}

ggplot(data = df) +
geom_bar(aes(x = number, y = y_value), stat = "identity") +
scale_x_continuous(breaks = seq(1, by = 1, length.out = 48),
labels = format_number_label)
enter image description here

关于r - ggplot2 中的小时刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65705121/

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