Converting ggplot to plotly - one line in differen

2019-09-14 18:40发布

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

enter image description here

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)

enter image description here

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

1条回答
不美不萌又怎样
2楼-- · 2019-09-14 19:25

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

enter image description here

ggplotly(plot)

enter image description here

查看更多
登录 后发表回答