如何在ggplot2中绘制Posix的小时数据?

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

我有一个数据框。

bvar time
0.000000000 2003-03-14 19:00:00
0.200000000 2003-03-14 20:00:00
0.044000000 2003-03-14 21:00:00

这里,时间是POSIXct。

str(tsdat$time)
 POSIXct[1:193], format: "2003-03-14 19:00:00" 

当我绘制时,我想控制X轴每小时显示一次。

ggplot(ts) +
  geom_line(aes(x=time, y=bvar))+
  theme(axis.text.x = element_text(angle = 0, hjust = 1))+
  scale_x_date(labels=date_format("%Y %H:%M")) + 
  ylab('BVAR [mm]')

ERROR

错误:无效输入:date_trans只与Date类对象一起工作。无效输入:date_trans只适用于Date类的对象。

如何才能做到时时彩呢?在另一个问题中,他们建议用 as.Date. 但这对我来说是行不通的,因为我的数据只有2天。

r ggplot2 posix
1个回答
1
投票

我想你可以用 scale_x_datetime 而不是POSIXct的 scale_x_date. 要想在X轴上得到每小时的休息时间,还需要添加 breaks = "1 hour".

library(ggplot2)
library(scales)

ggplot(ts) +
  geom_line(aes(x=time, y=bvar))+
  theme(axis.text.x = element_text(angle = 0, hjust = 1))+
  scale_x_datetime(labels=date_format("%Y %H:%M"), breaks = "1 hour") + 
  ylab('BVAR [mm]')

产量

plot using scale_x_datetime

数据

ts <- structure(list(bvar = c(0, 0.2, 0.044), time = structure(c(1047690000, 
1047693600, 1047697200), class = c("POSIXct", "POSIXt"), tzone = "")), row.names = c(NA, 
-3L), class = "data.frame")
© www.soinside.com 2019 - 2024. All rights reserved.