John
John

Reputation: 1828

R plotly add_trace to a chart with color groups

For data set mtcars, I want to plot a scatter plot (wt v.s. mpg) with am as the color group.

Then I want to add a trace from (2,15) to (3,25).

mtcars$am = as.character(mtcars$am)
plot_ly(mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>% 
    add_trace(x = c(2,15), y = c(3,25), mode="lines")

The code without add_trace works fine. How to add this line?

Upvotes: 2

Views: 2800

Answers (1)

Edgar Santos
Edgar Santos

Reputation: 3514

Option 1:

library(plotly)
library(ggplot2)
p <- ggplot(mtcars) + geom_point(aes(x = wt, y =  mpg, col = am)) + geom_segment(aes(x = 2, y = 3, xend = 15, yend = 25))
ggplotly(p)

Option 2:

plot_ly() %>% 
add_trace(data = mtcars,x = ~ wt, y= ~ mpg, color = ~ am, type='scatter', mode = 'markers') %>%
add_trace( x = c(2,15, rep(NA,nrow(mtcars))), y = c(3,25,rep(NA,nrow(mtcars))), mode="lines")

enter image description here

Upvotes: 1

Related Questions