2016-12-21 15 views
4

我想在plotly中繪製折線圖,​​以便它的整個長度上沒有相同的顏色。顏色是連續的。在ggplot2中很容易,但是當我使用ggplotly函數將它翻譯爲plotly函數時,變量確定顏色的行爲就像分類變量。ggplot2和使用ggplotly繪製的不同行爲

require(dplyr) 
require(ggplot2) 
require(plotly) 

df <- data_frame(
    x = 1:15, 
    group = rep(c(1,2,1), each = 5), 
    y = 1:15 + group 
) 

gg <- ggplot(df) + 
    aes(x, y, col = group) + 
    geom_line() 

gg   # ggplot2 
ggplotly(gg) # plotly 

GGPLOT2(期望的): enter image description here plotlyenter image description here

我發現一個變通的是,另一方面,在奇怪行爲ggplot2

df2 <- df %>% 
    tidyr::crossing(col = unique(.$group)) %>% 
    mutate(y = ifelse(group == col, y, NA)) %>% 
    arrange(col) 

gg2 <- ggplot(df2) + 
    aes(x, y, col = col) + 
    geom_line() 

gg2 
ggplotly(gg2) 

我也沒有找到一個方法如何直接做到這一點。也許根本沒有解決辦法。有任何想法嗎?

回答

3

看起來ggplotly將group視爲一個因素,即使它是數字。你可以使用geom_segment作爲一種變通方法,以確保段每對點之間繪製:

gg2 = ggplot(df, aes(x,y,colour=group)) + 
    geom_segment(aes(x=x, xend=lead(x), y=y, yend=lead(y))) 

gg2 

enter image description here

ggplotly(gg2) 

enter image description here

關於@ RAWR的(現已刪除)的評論,我覺得如果要將線條顏色映射到連續變量,則group應該是連續的。下面是OP的例子擴展到group列,它是連續的,而不是隻有兩個離散的類別。下面

set.seed(49) 
df3 <- data_frame(
    x = 1:50, 
    group = cumsum(rnorm(50)), 
    y = 1:50 + group 
) 

情節gg3使用geom_line,但我也包括在內geom_point。你可以看到ggplotly正在繪製點。但是,沒有行,因爲沒有兩個點具有相同的值group。如果我們沒有包括geom_point,圖表將是空白的。

gg3 <- ggplot(df3, aes(x, y, colour = group)) + 
    geom_point() + geom_line() + 
    scale_colour_gradient2(low="red",mid="yellow",high="blue") 

gg3 

enter image description here

ggplotly(gg3) 

enter image description here

切換到geom_segment給了我們,我們希望與ggplotly線。但是,請注意,線條顏色將基於段中第一個點的值group(無論是使用geom_line還是geom_segment),因此可能會出現以下情況:要在每個(x,y)之間插入值group )爲了配對以便獲得更流暢的色彩層次:

gg4 <- ggplot(df3, aes(x, y, colour = group)) + 
    geom_segment(aes(x=x, xend=lead(x), y=y, yend=lead(y))) + 
    scale_colour_gradient2(low="red",mid="yellow",high="blue") 

ggplotly(gg4) 

enter image description here

+0

這也是面面俱到!非常感謝 –