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:
df$group
.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)))
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:
Any idea?
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)))