簡體   English   中英

如何在R中的plotly線圖中添加圖例?

[英]How do I add legends in a groupby line plot in plotly in R?

我試圖在圖表的分組線圖中為每一行添加圖例但我找不到相關文檔。 這是沒有圖例的代碼(來自官方文檔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')))
      )
      )
    )
  )

在底部添加布局命令將工作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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM