heds1
heds1

Reputation: 3448

R Plotly legend ordering with multiple categories

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:

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
    )

Thanks for reading and any suggestions.

Upvotes: 1

Views: 1301

Answers (1)

Nir Graham
Nir Graham

Reputation: 5157

I struggled with this myself today, and came across your post in the process.

I found that plotly.js side introduced a legendrank feature around April 2021, but this doesnt seem to be reflected in the R Plotly documentation, though I tested and it is a working feature that came into plotly version 4.10.0

dat %>%
  plot_ly(
    type = "scatter",
    mode = "lines+markers",
    x = ~ year,
    y = ~ value,
    color = ~ I(colour),
    linetype = ~ I(linetype),
    name = ~ group,
    legendrank = ~ as.integer(group)
  )

Upvotes: 1

Related Questions