如何在R中以图方式在groupby线图中添加图例?

时间:2019-04-05 14:10:13

标签: r plotly

我正在尝试为plotly中的分组线图中的每条线添加图例,但找不到相关文档。 这是不带图例的代码(官方文档https://plot.ly/r/group-by/中的代码)。

library(plotly)

p <- plot_ly(
  type = 'scatter',
  x = mtcars$hp,
  y = mtcars$qsec,
  text = paste("Make: ", rownames(mtcars),
               "<br>hp: ", mtcars$hp,
               "<br>qsec: ", mtcars$qsec,
               "<br>Cyl: ", mtcars$cyl),
  hoverinfo = 'text',
  mode = 'markers',
  transforms = list(
    list(
      type = 'groupby',
      groups = mtcars$cyl,
      styles = list(
        list(target = 4, value = list(line =list(color = 'blue'))),
        list(target = 6, value = list(line =list(color = 'red'))),
        list(target = 8, value = list(line =list(color = 'black')))
      )
      )
    )
  )

1 个答案:

答案 0 :(得分:0)

在底部添加布局命令将起作用layout(showlegend = TRUE)。可以使用library(dplyr)包通过管道进行操作,如下所示:

library(plotly)
library(dplyr)

p <- plot_ly(
  type = 'scatter',
  x = mtcars$hp,
  y = mtcars$qsec,
  text = paste("Make: ", rownames(mtcars),
               "<br>hp: ", mtcars$hp,
               "<br>qsec: ", mtcars$qsec,
               "<br>Cyl: ", mtcars$cyl),
  hoverinfo = 'text',
  mode = 'markers',
  transforms = list(
    list(
      type = 'groupby',
      groups = mtcars$cyl,
      styles = list(
        list(target = 4, value = list(line =list(color = 'blue'))),
        list(target = 6, value = list(line =list(color = 'red'))),
        list(target = 8, value = list(line =list(color = 'black')))
      )
      )
    )
  ) %>%
layout(showlegend = TRUE)