R+Plotly:自定义图例条目
R+Plotly: Customize Legend Entries
我一定遇到了少于一个班轮的问题,
但请看下面的代码片段:我无法使用图例选项在图例中输入我想要的文本作为物种名称(例如,“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 认为图例名称与每条轨迹相关联,而不是与图例本身相关联。因此,必须在每个跟踪上重新定义名称。如果您不想修改原始数据集,则必须按 Species 过滤它并一次添加一个具有新名称的轨迹,如下所示:
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')))
在更复杂的情况下,最好确实修改数据集本身或使用循环。这里有一个关于更复杂案例的类似问题:Manipulating legend text in R plotly and the reference documentation on plotly legend names is here: https://plotly.com/r/legend/#legend-names
我一定遇到了少于一个班轮的问题, 但请看下面的代码片段:我无法使用图例选项在图例中输入我想要的文本作为物种名称(例如,“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 认为图例名称与每条轨迹相关联,而不是与图例本身相关联。因此,必须在每个跟踪上重新定义名称。如果您不想修改原始数据集,则必须按 Species 过滤它并一次添加一个具有新名称的轨迹,如下所示:
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')))
在更复杂的情况下,最好确实修改数据集本身或使用循环。这里有一个关于更复杂案例的类似问题:Manipulating legend text in R plotly and the reference documentation on plotly legend names is here: https://plotly.com/r/legend/#legend-names