简体   繁体   中英

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: 在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM