如何在`ggplot2`中格式化轴日期_时间标签?

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

我正在尝试绘制时间序列,并注意到 x 轴的 date_time 标签未按预期格式化。

library(ggplot2)
My_df = data.frame(My_datetime = seq(from = as.POSIXct("2019-05-21 8:00:00"), 
                                     to = as.POSIXct("2019-05-22 23:00:00"), 
                                     by = "10 min"),
                   My_data = sin(1:235))

ggplot(data = My_df) +
  geom_line(aes(x = My_datetime, y = My_data)) + 
  scale_x_datetime(breaks = c(as.POSIXct("2019-05-21 9:00:00"), 
                              as.POSIXct("2019-05-21 15:00:00"), 
                              as.POSIXct("2019-05-22 21:00:00")), 
                   labels=scales::date_format("%m-%d %H:%M"))

我只想显示三个 x 轴标签:

05-21 09:00
05-21 15:00
05-22 21:00
。但是,它现在显示为
05-21 15:00
05-21 21:00
05-23 03:00
。我想知道如何解决这个问题?谢谢你。

r ggplot2 time-series axis-labels
1个回答
0
投票

时区会扰乱您的输出!为了安全起见,请使用

lubridate::as_datetime

library(ggplot2)
My_df = data.frame(My_datetime = seq(from = as.POSIXct("2019-05-21 8:00:00"), 
                                     to = as.POSIXct("2019-05-22 23:00:00"), 
                                     by = "10 min"),
                   My_data = sin(1:235))

ggplot(data = My_df) +
  geom_line(aes(x = My_datetime, y = My_data)) + 
  scale_x_datetime(breaks = c(lubridate::as_datetime("2019-05-21 9:00:00"), 
                              lubridate::as_datetime("2019-05-21 15:00:00"), 
                              lubridate::as_datetime("2019-05-22 21:00:00")), 
                   labels=scales::date_format("%m-%d %H:%M"))

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