I have a data.frame that I'm trying to plot using plotly. I want to do a line plot with two variables and set the marker color based on a third variable. Below example shows what this looks like using mtcars as a sample dataset.
library(data.table)
library(plotly)
plot_ly(as.data.table(mtcars)[order(wt)]) %>%
add_trace(x = ~wt, y = ~mpg, color = ~vs, type = 'scatter', mode = 'lines+markers')
In my actual dataset, as in mtcars, the variable can take discrete values (0 or 1). By default plotly treats it as a continuous variable with a colorbar in the legend. I would like to show only two colors corresponding to the two values the variable can assume and not show any color bar.
I've tried setting the variable as a factor but that returns two line plots, which is not what I want:
plot_ly(as.data.table(mtcars)[order(wt)]) %>%
add_trace(x = ~wt, y = ~mpg, color = ~as.factor(vs), type = 'scatter', mode = 'lines+markers')
I've also tried to set the marker color alone based on the third variable:
plot_ly(as.data.table(mtcars)[order(wt)]) %>%
add_trace(x = ~wt, y = ~mpg, color = ~as.factor(vs), type = 'scatter', mode = 'lines+markers')
This works but I'm not able to specify the colors for the two levels. I've tried using marker = list(colors = c('green', 'red', ...) without any success.
To summarize, I want to display a single line plot (uniform color) for two variables with markers set to two discrete colors (no colorbar) that I specify based on the value of a third variable.


