I'm having trouble specifying the order of the legend in a plotly R plot. This is similar to this unresolved post.
These made-up data are grouped by the group variable with two levels, "A" and "B". There are two aesthetic properties separating these groups:
- "A" is red with a solid line;
- "B" is blue with a dashed line.
The desired output is a legend with the blue dotted line, corresponding to the "B" group, at the top.
library(plotly)
library(dplyr)
set.seed(1)
dat <- tibble(
year = rep(2010:2019, 2),
group = factor(rep(c("A", "B"), each = 10), levels = c("B", "A")),
value = c(
rnorm(10, 10, 2),
rnorm(10, 14, 2)
),
colour = rep(c("red", "blue"), each = 10),
linetype = factor(rep(c("solid", "dot"), each = 10), levels = c("solid", "dot"))
)
If we ignore linetype for now, the legend is correct in that it has "B" above "A" (based on the factor levels for group variable).
dat %>%
plot_ly(
type = "scatter",
mode = "lines+markers",
x = ~ year,
y = ~ value,
color = ~ I(colour),
name = ~ group
)
However, when we add linetype in, the legend order is reverted to the default (with "A" above "B"):
dat %>%
plot_ly(
type = "scatter",
mode = "lines+markers",
x = ~ year,
y = ~ value,
color = ~ I(colour),
linetype = ~ I(linetype),
name = ~ group
)
Changing the factor levels of linetype doesn't fix the legend, it just breaks the mapping from linetype to the data:
dat %>%
mutate(linetype = factor(linetype, levels = c("dot", "solid"))) %>%
plot_ly(
type = "scatter",
mode = "lines+markers",
x = ~ year,
y = ~ value,
color = ~ I(colour),
linetype = ~ I(linetype),
name = ~ group
)
- R version 4.0.3
- plotly version 4.9.2.1
Thanks for reading and any suggestions.