Search code examples
rggplot2plotplotlyr-plotly

How to add vertical lines connecting two sets of points using plotly in R?


I want to create a plot that adding vertical lines between two sets of points using plotly in R. I know how to do this in ggplot2, and I know I can use the ggplotly function to convert the ggplot2 object to a plotly object. However, I would like to learn how do this directly using plotly.

Below is an example code creating an example data frame and use ggplot2 and ggplotly to create the plot I want.

# Load packages
library(tidyverse)
library(plotly)

# Create example dataset
dat <- tibble(
  Group = factor(c(2, 2, 2, 1, 1, 1)),
  Date = as.Date(rep(c("2020-01-01", "2020-01-02", "2020-01-03"), times = 2)),
  value = c(1, 2, 1, 5, 5.5, 6)
)

g <- ggplot(dat, aes(x = Date, y = value, color = Group)) +
  geom_point() +
  scale_color_brewer(type = "qual", palette = "Set1") +
  geom_line(aes(group = Date), color = "black") +
  theme_minimal()

ggplotly(g)

enter image description here

Here is an other example code I try to create the same plot using plotly. The final step I want to do is to add the horizontal lines like the previous plot.

plot_ly(dat, x = ~Date, y = ~value, color = ~factor(Group), 
        colors = "Set1",
        type = "scatter", mode = "markers")

enter image description here


Solution

  • This appears to do

    plot_ly(dat, x = ~Date, y = ~value, color = ~factor(Group), 
            colors = "Set1",
            type = "scatter", mode = "markers") %>%
      add_segments(data=dat,  
                   x = ~Date[Group == 1], 
                   xend= ~ Date[Group == 1], 
                   y = ~value[Group == 1], 
                   yend = ~value[Group ==2],
                   color = ~ Group[Group == 2], 
                   line=list(color="black"), 
                   showlegend=FALSE)  
    

    enter image description here