问题
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?
回答1:
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")
来源:https://stackoverflow.com/questions/44915844/r-plotly-add-trace-to-a-chart-with-color-groups