2015-09-25 158 views
1

我有data.frame与3列作为名称,变量&值。 我data.frame是像(每个值以逗号分隔)如何使用ggplot2在Y轴上设置时间范围(HH:MM:SS)?

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然后写代码等

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

与具有1000步骤即将以秒适当的时间范围Y轴现在期望曲线图。

但是在几秒钟内我想以hh:mm:ss格式代替时间,其范围为&。我通过Stack Overflow搜索了R中的cookbook,但没有得到正确的结果。任何一个如果可以请建议一些解决方案。

回答

0

哈克,但这个工程:

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 

+1

PS - 我用@ jennybryan的[reprex()包(https://github.com/jennybc/reprex)复制和粘贴代码和图像。让生活变得非常简单! – potterzot

+0

感谢您的回答:)。实际上cycle3的总长度大于2小时,但它显示1:40:00这是错误的。我明白你手动缩放它,并通过设置它2:00:00我们可以得到正确的图。我担心的是,我们可以在没有手动提供比例的情况下进行绘制ggplot2应该能够自动添加时间戳并提供正确的比例。如果有遗漏或错误,请提出建议。 – Roger

+0

你能帮忙吗?我试图完成它,我不能绘制正确的情节。 – Roger

相关问题