Gautam
Gautam

Reputation: 2753

Set marker color in plotly scatter plot based on data.frame column

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')

The output looks like: enter image description here

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')

enter image description here

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.

enter image description here

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.

Upvotes: 2

Views: 4152

Answers (1)

Sada93
Sada93

Reputation: 2835

One way to do it is to set the color of each marker manually as follows, you can specify the colors based on the value of the third variable vs in the recode() function below.

data <- data.frame(mtcars,stringsAsFactors = F)
data <- data %>% 
  arrange(wt) %>% 
  mutate(vs = as.character(vs),
         color = recode(vs,`1` = "red",
                        `0` = "blue"))

plot_ly(data) %>% 
       add_trace(x = ~wt, y = ~mpg, type = 'scatter', mode = 'lines+markers',
                 marker = list(color = ~color))

Upvotes: 1

Related Questions