0

My data frame looks like this:

Column A Column B Column C
7 groupA red
8 groupA red
5 groupB grey
4 groupC blue
5 groupD yellow

Here is my code:

p <- plot_ly(df) %>%
      add_markers(color=df$B,
                  colors=c("red", "grey", "blue", "yellow")

It works fine when there are only four groups. But my df has more than 10 groups. and when I provide my color vector, the color mapping is wrong: I got groupA-grey, groupB-yellow, groupC-blue, etc...

I tried to understand how does this function order the elements in colB, but it's a bored work when you have more than 10 groups with numbers and letters in them. so How can I color the markers by colB and give the real color by colC in plot_ly? I know I can use breaks in scale_color_manual() to align colors and groups. but I didnt find something similiar in plot_ly.

1 Answer 1

0

One option would be to use a named vector of colors similar to what is recommended to do when using scale_color_manual in ggplot2:

Note: For the sake of the example I dropped group C from your example data to show that using a named vector gives a consistent assignment of colors.

df <- data.frame(
  A = c(7L, 8L, 5L, 4L, 5L),
  B = c("groupA", "groupA", "groupB", "groupD", "groupD")
)

library(plotly)

plot_ly() %>%
  add_markers(
    x = df$B,
    y = df$A,
    color = df$B,
    colors = c(groupA = "red", groupB = "grey", groupC = "blue", groupD = "yellow") 
  )

2
  • This is exactly what I want! Thanks sooo much. BTW, I'd very greatful it you can also teach me how to make this vector c(groupA = "red", groupB = "grey", groupC = "blue", groupD = "yellow") with colA and colB with some function rather than manually type it out. I have a strong feeling that it would be very helpful in my later work Commented Jun 2 at 7:37
  • df |> dplyr::distinct(Column.B, Column.C) |> tibble::deframe() will give you a named vector.
    – stefan
    Commented Jun 2 at 8:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.