我一定遇到了少于一行的问题,但请看下面的片段:我不能使用图例选项在图例中输入我想要的文本作为物种的名称(例如,"foo1"、"foo2"、"foo3"(。请注意,我不想更改原始数据集(在本例中为iris(。
有什么建议吗?
library(tidyverse)
library(plotly)
plot_ly(iris, x = ~Sepal.Length,
y = ~Sepal.Width,
type = 'scatter', color = ~Species,
symbol = ~Species,
mode = 'markers') %>%
layout(legend=list(title=list(text='My title')))
Plotly认为图例名称与每个跟踪相关联,而不是与图例本身相关联。因此,必须在每个跟踪上重新定义名称。如果你不想修改原始数据集,你必须按物种对其进行过滤,并一次添加一个新名称的痕迹,类似于这样的东西:
library(tidyverse)
library(plotly)
plot_ly(iris %>% filter(Species == "setosa"),
x = ~Sepal.Length,
y = ~Sepal.Width,
type = 'scatter',
color = ~Species,
symbol = ~Species,
mode = 'markers',
name = "foo 1") %>%
add_trace(data = iris %>% filter(Species == "versicolor"),
x = ~Sepal.Length,
y = ~Sepal.Width,
type = 'scatter',
color = ~Species,
symbol = ~Species,
mode = 'markers',
name = "foo 2") %>%
add_trace(data = iris %>% filter(Species == "virginica"),
x = ~Sepal.Length,
y = ~Sepal.Width,
type = 'scatter',
color = ~Species,
symbol = ~Species,
mode = 'markers',
name = "foo 3") %>%
layout(legend=list(title=list(text='My title')))
在更复杂的情况下,最好确实修改数据集本身或使用循环。关于更复杂的情况,这里有一个类似的问题:在R plotly中操纵图例文本,关于plotly图例名称的参考文档在这里:https://plotly.com/r/legend/#legend-名称