2017-02-20 55 views
2

數據:指定自定義顏色漸變到POSIXct時間序列

df1 <- structure(list(Index = 1:11, Duration = structure(c(1487577655, 
1487577670, 1487577675, 1487577680, 1487577685, 1487577680, 1487577700, 
1487577705, 1487577695, 1487577700, 1487577680), class = c("POSIXct", 
"POSIXt"), tzone = "")), .Names = c("Index", "Duration"), class = "data.frame", row.names = 3:13) 

現在我構造圖如下:

g1 <- ggplot(df1, aes(x=Index, y=Duration, color=Duration))+ 
geom_point()+ 
geom_line()+ 
scale_y_datetime(labels=date_format("%M:%S")) 

因爲它是現在,圖形的顏色設置爲默認的「黑「到」藍色「漸變。

問題是,我試圖給數據分配自定義漸變時出現錯誤。

對於非POSIXct對象:

scale_color_gradient("Duration",low="#D80427", high="#07a0ff",space="Lab") 

作品,但我得到下面的錯誤與POSIXct對象df1$Duration作爲解釋變量:

錯誤Ops.POSIXt((X - from [1]),diff(from)):'/'未定義 for「POSIXt」objects

是否有不同的梯度函數當我繪製一個POSIXct對象時,我需要使用它嗎?

+0

嘗試'顏色= as.numeric(持續時間))' – zx8754

回答

2

您可以使用trans = time_trans()

library(ggplot2) 
library(scales) 
g1 + 
    scale_color_gradient("Duration", low = "#D80427", high = "#07a0ff", 
         trans = time_trans()) 

enter image description here

如果您希望圖例中標籤的另一個format,請添加例如labels = format(pretty(df1$Duration), "%M:%S")

+0

@HenryRice這應該是被接受的答案,隨時可以改變。 – zx8754

1

我們可以轉換日期號碼顏色:

library(ggplot2) 
library(scales) 

ggplot(df1, aes(x = Index, y = Duration, color = as.numeric(Duration))) + 
    geom_point() + 
    geom_line() + 
    scale_y_datetime(labels = date_format("%M:%S")) + 
    scale_color_gradient("Duration", low = "#D80427", high = "#07A0FF", 
         labels = c("00", "10", "20", "30", "40")) 

至於建議的@Henrik,避免硬編碼標籤下面使用:

# avoid hardcoding labels using pretty() 
ggplot(df1, aes(x = Index, y = Duration, color = as.numeric(Duration))) + 
    geom_point() + 
    geom_line() + 
    scale_y_datetime(labels = date_format("%M:%S")) + 
    scale_color_gradient("Duration", low = "#D80427", high = "#07A0FF", 
         breaks = pretty(as.numeric(df1$Duration)), 
         labels = format(pretty(df1$Duration), "%M:%S")) 
+1

完美的作品。我的第二個擔心是如果轉換爲數字保存了時間之間的相對距離,並且前兩個數值的快速測試顯示1487577670 - 1487577655 = 15,這相當於使用第一個到時間值1:10 - 00:55 = 15.所以它看起來像是一個很好的解決方案。謝謝您的幫助! – Mako212

+0

@ zx8754我認爲如果你使用'breaks = pretty(as.numeric(df1 $ Duration)),labels = format(pretty(df1 $ Duration),「%M:%S」),你可以避免對標籤進行硬編碼。 )'(或任何你想要的格式)。 – Henrik

+0

@亨利克謝謝你,更新了帖子。 – zx8754