[英]How do I add legends in a groupby line plot in plotly in R?
I am trying to add legend for each line in a grouped line plot in plotly but I cannot find the relevant documentation. 我试图在图表的分组线图中为每一行添加图例但我找不到相关文档。 Here is the code without the legends (code from the official documentation https://plot.ly/r/group-by/ ).
这是没有图例的代码(来自官方文档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')))
)
)
)
)
Adding a layout command at the bottom will work layout(showlegend = TRUE)
. 在底部添加布局命令将工作
layout(showlegend = TRUE)
。 This can work by being piped in using the library(dplyr)
package as shown here: 这可以通过使用
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.