用ggplot和chron绘图 - 标签更改为%H:%M:%S

时间:2017-05-17 22:52:34

标签: r ggplot2 chron

我正在使用该课程的一些chron数据' times'并在散点图中绘制它。但是,我希望x轴%H:%M:%S上的变量标签为Tim.V格式。只需将scale_x_continuous(labels = "%H:%M:%S")添加到下面的代码中似乎无法解决问题。我不需要以任何方式转换数据 - 只是x轴上标签的格式。有关如何做到这一点的任何见解?看起来应该很简单。

doeplotnet <- ggplot(division, aes(x =Tim.V, y = Age)) + geom_point() + scale_x_reverse()

示例数据(年龄为数字,Tim.V为&#39;次&#39;)

Age     Tim.V
40       00:33:08
36       00:59:27
29       01:05:33
52       00:49:14
49       01:08:00
44       00:30:45

2 个答案:

答案 0 :(得分:0)

这很有效:

library(chron)
library(ggplot2)
division$Tim.V <- times(division$Tim.V)
breaks2 <- seq(min(division$Tim.V), max(division$Tim.V), length.out = 5)
labels2 <- times(breaks2)

doeplotnet <- ggplot(division, aes(x = as.numeric(Tim.V), y = Age)) + geom_point() +
 scale_x_reverse(labels = labels2, breaks = breaks2)
doeplotnet

enter image description here

division <- read.table(text= "Age     Tim.V
40       00:33:08
36       00:59:27
29       01:05:33
52       00:49:14
49       01:08:00
44       00:30:45", stringsAsFactors=TRUE, header = TRUE)

答案 1 :(得分:0)

您还可以使用lubridate::ymd_hms转换为带有虚拟日期的日期时间,并使用ggplot2进行绘制:

library(tidyverse); library(lubridate)
mydata3 <- mydata2 %>%
  mutate(time3 = lubridate::ymd_hms(paste(
    "2000-01-01", hour(time2), minute(time2), second(time2))))

ggplot(mydata3, aes(x=time3, y=pending, color=server, group=tradedate)) +
    geom_point() +
    facet_wrap(~ tradedate)

enter image description here

使用的样本数据:

mydata2 <-
  data_frame(time2 = new(
    "Period",
    .Data = c(23, 23, 42, 42, 24, 24, 42, 42),
    year = c(0,  0, 0, 0, 0, 0, 0, 0),
    month = c(0, 0, 0, 0, 0, 0, 0, 0),
    day = c(0,
            0, 0, 0, 0, 0, 0, 0),
    hour = c(14, 14, 14, 14, 14, 14, 14, 14),
    minute = c(5, 5, 5, 5, 6, 6, 6, 6)
  ),
  pending = runif(8),
  server = "server1",
  tradedate = rep(ymd(c(20190101, 20190102)), 4)
  )