2017-04-14 28 views
0

我想有圖,其中在一行在不同顏色下面的例子中繪製成一條線:轉換ggplot到plotly - 不同顏色

test_data <- 
    data.frame(
     var0 = 100 + c(0, cumsum(runif(49, -20, 20))), 
     var1 = 150 + c(0, cumsum(runif(49, -10, 10))), 
     date = seq(as.Date("2002-01-01"), by="1 month", length.out=100) 
    ) 

plot <- ggplot(test_data, aes(x = date)) + 
    geom_line(aes(y = var0, group = 1, colour = c(rep(c("a", "b"), each = 25), rep("a", 50)))) + 
    geom_line(aes(y = var1, colour = "var1")) 
plot 

enter image description here

我有什麼相同的情節在情節或R中的一些其他交互式庫(以便在某些特定的線/點上移動鼠標時可以顯示帶有某些數據的標籤)。當我使用ggplotly我得到這樣的

library(plotly) 
ggplotly(plot) 

enter image description here

你知道如何紅色和綠色線一條線結合(在ggplot它是通過group=1參數做)?

+0

爲什麼'顏色= C(REP(C( 「A」, 「B」 ),每個= 25),rep(「a」,50)))'? –

+0

這只是一個例子,我想要有兩條不同顏色的線條,此線條使得數值在26和50之間變爲綠色(組b),而所有其他紅色(組a)。這個問題的主要觀點是如何使'積極'認爲這個序列應該仍然是一條線,而不是兩條。 – jjankowiak

回答

1

問題出現了,因爲在小組任務中沒有26:50行(大約在2004年和2005年)的「a」數據。 ggplot強制連接25行和51行的點時出現的行跳轉,這些行出現在ggplotly中。

這是我嘗試用數據的長型:

t2 <- test_data[26:50, ] 
t2$gp <- "b" 
test_data$gp <- "a" 

df <- rbind(test_data, t2) 
df <- gather(df, var, value, -date, - gp) 

plot <- ggplot() + 
    geom_line(data=df %>% filter(var=="var0"), aes(x=date, y=value, colour=gp)) + 
    geom_line(data=df %>% filter(var=="var1"), aes(x=date, y=value, colour=var)) 

enter image description here

ggplotly(plot) 

enter image description here