Search code examples
rplotlyr-plotly

Problem with custom colors for both lines and markers with `plot_ly`


Let's assume that I want to use custom colors for a line+marker plotly plot. It is quite straighforward to use the colors and color arguments of plot_ly() but as soon as I want to modify the markers themselves (using the marker argument) I encounter difficulties and didn't find help to solve this specific issue on the net. Can someone tell me what am I doing wrong?

# Underlying data
tmp <- mpg %>%
  group_by(class,manufacturer) %>%
  summarise(models=n())

# Works as expected
tmp %>% 
  plot_ly(x=~manufacturer, 
          y=~models, 
          group=~class,
          type="scatter",
          color=~class, 
          colors = scales::hue_pal()(length(n_distinct(tmp$class))), #ggplot colors
          mode="lines+markers")

# Issue with markers > idea behind is to have a white center and a marker line with the same color as the line itself
tmp %>% 
  plot_ly(x=~manufacturer, 
          y=~models, 
          group=~class,
          type="scatter",
          color=~class, 
          colors = scales::hue_pal()(n_distinct(tmp$class)),
          marker = list(color = 'rgba(255, 255, 255, 1)',
                        line = list(color = scales::hue_pal()(n_distinct(tmp$class)))),
          mode="lines+markers")

Solution

  • This may seem a little strange, but the beautifully simple solution in your case is to drop:

    line = list(color = scales::hue_pal()(n_distinct(tmp$class))))
    

    and only inlcude:

    line = list(width = 3)
    

    Here's your plot now:

    enter image description here

    Complete code:

    # Underlying data
    tmp <- mpg %>%
      group_by(class,manufacturer) %>%
      summarise(models=n())
    
    
    # Issue with markers > idea behind is to have a white center and a marker line with the same color as the line itself
    tmp %>% 
      plot_ly(x=~manufacturer, 
              y=~models, 
              group=~class,
              type="scatter",
              color=~class, 
              colors = scales::hue_pal()(n_distinct(tmp$class)),
              marker = list(color = 'rgba(255, 255, 255, 1)',
                            line = list(width = 3)),
              mode="lines+markers")
    tmp