2015-09-25 161 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

相關問題