R将add_trace绘制为带有颜色组的图表

时间:2017-07-05 01:33:15

标签: r plotly

对于数据集libs\db public function allObjects($query, $typeofobject, $params = array()) { $this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); $stmt = $this->connection->prepare($query); $stmt->execute($params); // this instead of setAttribute does the same thing (yes, only one parameter) foreach ($parametry as $p) { $stmt->bindParam(1, $p, PDO::PARAM_INT); } $stmt->execute(); // -------- $stmt->setFetchMode(PDO::FETCH_CLASS, 'app\\models\\' . $typeofobject); return $stmt->fetchAll(); } ,我想绘制散点图(mtcars v。。wt)并将mpg作为颜色组。

然后我想添加从(2,15)到(3,25)的痕迹。

am

没有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") 的代码可以正常工作。如何添加这一行?

1 个答案:

答案 0 :(得分: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")

enter image description here