我想绘制包含数字和持续时间的数据。为了转换字符向量,我选择了lubridate
包。不幸的是,持续时间始终在x轴上以秒为单位打印:
set.seed(20161027)
a <- c("00:30:45", "00:59:07", "01:08:30", "02:10:09", "02:20:53")
b <- rnorm(n = 5)
example <- data.frame(a, b)
# This is what I want
ggplot(data = example, aes(x = a, y = b)) +
geom_point()
library(lubridate)
a <- hms(a)
a <- as.duration(a)
example <- data.frame(a, b)
ggplot(data = example, aes(x = a, y = b)) +
geom_point()
答案 0 :(得分:2)
不确定为什么要使用lubridate
执行此操作。使用as.POSIXct
:
a <- as.POSIXct(c("00:30:45", "00:59:07", "01:08:30", "02:10:09", "02:20:53"),
format="%H:%M:%S")
b <- rnorm(n = 5)
example <- data.frame(a, b)
ggplot(data = example, aes(x = a, y = b)) +
geom_point()
答案 1 :(得分:1)
我认为@ HubertL的解决方案已经足够好了,但如果你坚持使用lubridate
,你可以试试
library(lubridate)
set.seed(20161027)
a <- c("00:30:45", "00:59:07", "01:08:30", "02:10:09", "02:20:53")
b <- rnorm(5)
example <- data.frame(a=hms(a), b=b)
ggplot(data = example, aes(x = a$hour + a$minute / 60 + a$second / 60^2, y = b)) +
geom_point() +
scale_x_continuous(name="a",
breaks=c(0.5, 1, 1.5, 2),
labels=c("00:30", "01:00", "01:30", "02:00"))