✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

R - Legend order with several categories

Hi all,

I am trying to get a simple scatterplot legend organized properly.
On a simple example, I can order legend elements (e.g. color) using factor levels:

Dummy data:

# Points coordinates
dataX = rnorm(1:100)
dataY = 1:100
# Categories
letter = rep(LETTERS[1:10], each=10)
number = rep(1:2, 50)
# 10 colors palette
colors = colorRampPalette(c("blue", "red"))(10)
names(colors) = unique(letter)

Simple scatterplot:

plot_ly( type = "scattergl",
         mode = "markers",
         data = data.frame(colX = dataX, colY = dataY, colLetter = letter, colNumber = number),
         x = ~colX,
         y = ~colY,
         color = ~factor(colLetter),
         colors = colors)

Reorganized color legend using factor levels:

plot_ly( type = "scattergl",
         mode = "markers",
         data = data.frame(colX = dataX, colY = dataY, colLetter = letter, colNumber = number),
         x = ~colX,
         y = ~colY,
         color = ~factor(colLetter, levels = rev(names(colors))),
         colors = colors)

That seems perfect.
However, when I try to add a second categorization (as symbol), I am unable to control the order of legend anymore.


plot_ly( type = "scattergl",
         mode = "markers",
         data = data.frame(colX = dataX, colY = dataY, colLetter = letter, colNumber = number),
         x = ~colX,
         y = ~colY,
         color = ~factor(colLetter, levels = rev(names(colors))),
         symbol = ~factor(colNumber),
         colors = colors)

In this example, legend groups letters with numbers as expected.
However, I would expect letters to be listed in reverse order as in previous example but it does not seem to be the case.

I noticed this while playing with legendgroup parameter but it does not seem related to it. It looks like factor order is ignored as soon as you have several categories to be merged in legend.

Is this expected behavior ?
Could you suggest a method to keep control of my legend ordering ?

Thank you for your help.

Just adding to the observations:
color factor levels also affect the plotting order (first levels dots end-up ‘behind’ others).

When adding symbol as in previous examples, the plotting order also comes back to a default and there is no way to influence that with levels anymore.