Search code examples
rplotlygoogle-maps-markerscolor-mapping

R plot_ly How to set the color of markers in add_markers() with my own color vector in a correct mapping way


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.


Solution

  • 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") 
      )