我正在尝试为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')))
)
)
)
)
在底部添加布局命令将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)