本文介绍了R将带有颜色组的图表的add_trace绘制到图表上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于数据集mtcars
,我想绘制一个散点图(wt
vs. mpg
),其中am
作为颜色组.
For data set mtcars
, I want to plot a scatter plot (wt
v.s. mpg
) with am
as the color group.
然后我要添加一条从(2,15)到(3,25)的轨迹.
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")
不带add_trace
的代码可以正常工作.如何添加此行?
The code without add_trace
works fine. How to add this line?
推荐答案
选项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")
这篇关于R将带有颜色组的图表的add_trace绘制到图表上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!