R plotly add_trace to a chart with color groups

只谈情不闲聊 提交于 2019-12-07 18:35:42

问题


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

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