【问题标题】:R plotly add_trace to a chart with color groupsR plotly add_trace 到带有颜色组的图表
【发布时间】:2017-12-08 12:13:32
【问题描述】:

对于数据集mtcars,我想以am 作为颜色组绘制散点图(wtmpg)。

然后我想添加从 (2,15) 到 (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")

没有add_trace 的代码可以正常工作。这行怎么加?

【问题讨论】:

    标签: r plotly


    【解决方案1】:

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

    选项 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")
    

    【讨论】:

    • 有什么方法可以直接使用plot_ly?我的数据中有时间戳。 Plotly 对时间戳更友好。
    • 在选项2中,没有颜色。这就是难点。如果我们不需要 am 的颜色,删除 rep 不会改变任何东西。
    猜你喜欢
    • 2021-01-29
    • 2019-02-10
    • 2021-12-26
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2023-03-04
    相关资源
    最近更新 更多