ggplot2:秒和scale_x_time - HH:MM 而不是 HH:MM:SS

问题描述 投票:0回答:1

输入数据的结构如下

价格 日期
11111 6443 2022-01-03
22222 7400 2022-01-04
ggplot(data=d.2,aes(x=Seconds, y=Price)) + 
  geom_path(colour="blue") + 
  ylab("Price") + 
  xlab("Date") +
  coord_cartesian(xlim = c(7*3600+5*60, 15*3600+25*60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time()

现在我得到以下输出

尝试以我在此处找到的某些方式操纵scale_x_time,但似乎无法正确操作。

我想以小时和分钟为单位显示一天中的时间,这样它更适合我的 lowre x 轴。

r datetime ggplot2 scale seconds
1个回答
0
投票

在底层

scale_x_time
将秒数转换为
hms
对象。不幸的是,我没有找到一个选项来格式化
hms
以直接仅显示小时和分钟。但一个选择是先转换为日期时间:

library(ggplot2)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

d.2 <- data.frame(
  Price = c(11111L, 22222L),
  Seconds = c(6443L, 7400L),
  Date = c("2022-01-03", "2022-01-04")
)

ggplot(data = d.2, aes(x = Seconds, y = Price)) +
  geom_path(colour = "blue") +
  ylab("Price") +
  xlab("Date") +
  coord_cartesian(xlim = c(7 * 3600 + 5 * 60, 15 * 3600 + 25 * 60)) +
  facet_wrap(~Date, nrow = 1) +
  scale_x_time(
    labels = \(x) format(as_datetime(x, tz = "UTC"), "%H:%M")
  )
#> `geom_path()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?
#> `geom_path()`: Each group consists of only one observation.
#> ℹ Do you need to adjust the group aesthetic?

© www.soinside.com 2019 - 2024. All rights reserved.