rplotlyborderscatter-plotcolor-scheme

Adding multiple scatter border line to an R plotly scatter plot


I'm trying to produce a scatter plot using R's plotly with this example data.frame:

set.seed(1)
library(dplyr)
library(plotly)

df <- data.frame(x = runif(6, -3, 3), y = 1:6, group = sample(c("a", "b"), 6, replace = T), class = sample(c(T, F), 6, replace = T))

I would like to:

  1. Color-code the inside of the points by df$group.
  2. Color-code the borders of the points by df$class.

My question is how to achieve #2? I know how to color the borders with a single color:

plotly::plot_ly(type = "scatter",mode = "markers", x = df$x, y = df$y, color = df$group, marker = list(size = 13, line = list(color = 'black', width = 2)))

enter image description here

But trying something like:

df <- df %>% dplyr::mutate(border.color = ifelse(class, 'black', 'green'))
plotly::plot_ly(type = "scatter",mode = "markers", x = df$x, y = df$y, color = df$group, marker = list(size = 13, line = list(color = df$border.color, width = 2)))

doesn't work:

enter image description here

Any idea?


Solution

  • You need to distinguish mappings (varying a parameter depending on a variable) from set values. If you want to change the borders of the point you can map your variable to stroke as shown here:

    library(dplyr)
    library(plotly)
    
    set.seed(1)
    df <- data.frame(x = runif(6, -3, 3),
                     y = 1:6,
                     group = sample(c("a", "b"), 6, replace = T),
                     class = sample(c(T, F), 6, replace = T))
    
    plotly::plot_ly(data = df,
                    type = "scatter",
                    mode = "markers",
                    x = ~x,
                    y = ~y,
                    color = ~group,
                    stroke = ~class,
                    strokes = c(`TRUE`="black",`FALSE`="green"),
                    marker = list(size = 13, line = list(width = 2)))
    

    Example plot with stroke depending on class