Converting ggplot to plotly - one line in different colors

不想你离开。 提交于 2019-12-25 05:04:59

问题


I want to have plot where one line in drawn in different colors as in example below:

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

I what to have the same plot in plotly or some other interactive library in R (so that the lables with some data could be displayed when moving the mouse on some specific line/point). When I use ggplotly I get something like this

library(plotly)
ggplotly(plot)

Do you know how to combine red and green line in one line (in ggplot it is done through group=1 parameter)?


回答1:


The issue arises as there's no data for "a" for lines 26:50 (around 2004 and 2005) with the group assignment. The line jump when ggplot force join points from line 25 and line 51, which appear in ggplotly.

Here's my attempt with a long form of data:

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))

ggplotly(plot)



来源:https://stackoverflow.com/questions/43409858/converting-ggplot-to-plotly-one-line-in-different-colors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!