简体   繁体   English

根据data.frame列在绘图散点图中设置标记颜色

[英]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 . 我有一个data.frame ,我试图用绘制plotly I want to do a line plot with two variables and set the marker color based on a third variable. 我想用两个变量绘制line图,并根据第三个变量设置标记颜色。 Below example shows what this looks like using mtcars as a sample dataset. 下面的示例显示了使用mtcars作为样本数据集的情况。

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). 在我的实际数据集中,如mtcars ,变量可以采用离散值(0或1)。 By default plotly treats it as a continuous variable with a colorbar in the legend. 默认情况下,在图例中使用plotly将其视为连续变量。 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 . 这行得通,但我无法指定两个levels的颜色。 I've tried using marker = list(colors = c('green', 'red', ...) without any success. 我尝试使用marker = list(colors = c('green', 'red', ...)没有成功。

在此处输入图片说明

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. 一种方法是手动设置每个标记的颜色,如下所示,您可以根据第三个变量vs的值在下面的recode()函数中指定颜色。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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