如何使用ggplot2在Y轴上设置时间范围(HH:MM:SS)?

时间:2015-09-25 16:25:14

标签: r ggplot2 visualization data-visualization

我有data.frame,其中3列为Name,Variable&值。 我的data.frame就像(每个值以逗号分隔)

Name,Variable,Value   
a,cycle1,00:01:67
b,cycle1,00:05:20
c,cycle1,00:28:27
a,cycle2,00:02:58
b,cycle2,00:25:18
c,cycle2,00:27:45
a,cycle3,00:37:09
b,cycle3,00:29:18
c,cycle3,00:53:24

我想绘制一个堆积的条形图,其中X轴是可变的& Y轴是值

我写了以下脚本

Graph<- ggplot(data = dataFrame,
               aes(x = dataFrame$Variable, y = dataFrame$Value, fill = Name)) +
        geom_bar(stat = "identity")

通过上面的脚本图即将到来但是它没有在y轴上显示全范围,即使我无法在Y轴上用一些步长值改变范围。

我试过strptime,如下所示

dataFrame$TimeCol <- strptime(dataFrame$Value, format = "%H:%M:%S")

Graph <- ggplot(dataFrame, 
                aes(x=dataFrame$Variable, y=dataFrame$TimeCol,fill = dataFrame$Name)) + 
         geom_bar(color="black",stat = "identity")

现在也希望图表不会出现,Y轴范围就像2000,2100,2200 ...... 然后我尝试添加一个额外的列名称TimeInSeconds,实际上是将Value列转换为秒,然后编写代码,如

Graph <- ggplot(data = dataFrame,
                aes(x = dataFrame$Variable, y = dataFrame$TimeInSeconds, fill = Name)) +
         geom_bar(stat = "identity")

现在所需的图表,Y轴具有适当的时间范围,以秒为单位,步长为1000.

但是在几秒钟内代替时间,我想要的是hh:mm:ss格式,并且具有适当的范围&amp;步数值。我搜索了Stack Overflow,R中的食谱但是没有得到正确的结果。任何人如果可以请提出一些解决方案。

1 个答案:

答案 0 :(得分:0)

Hacky,但这有效:

library(ggplot2)

m <- matrix(c("a","cycle2", "00:01:57", 
              "b","cycle1", "00:05:20",
              "c","cycle1", "00:28:27",
              "a","cycle2", "00:02:58",
              "b","cycle2", "00:25:18",
              "c","cycle2", "00:27:45",
              "a","cycle3", "00:37:09",
              "b","cycle3", "00:29:18",
              "c","cycle3", "00:53:24"), nrow = 9, ncol=3, byrow=TRUE)

start_time = strptime("00:00:00", format = "%H:%M:%S")
end_time = strptime("01:00:00", format = "%H:%M:%S")
breaks = seq(0, 125, length.out = 6)
labels = c("00:00:00", "00:20:00", "00:40:00", 
           "01:00:00", "01:20:00", "01:40:00")

dataFrame <- data.frame(m)
names(dataFrame) <- c("Name","Variable","Value")
dataFrame$Time <- strptime(dataFrame$Value, format = "%H:%M:%S")
dataFrame$TimeInSeconds <- as.numeric(dataFrame$Time - start_time)

p <- ggplot(data = dataFrame) + 
  geom_bar(aes(x = dataFrame$Variable, 
               y = dataFrame$TimeInSeconds, 
               fill = factor(Name)), stat="identity") +
  scale_y_continuous(
    limits = c(0, 125),
    breaks = breaks,
    labels = labels

    )
p