如何固定散点图中某些变量的颜色

时间:2020-11-02 14:39:24

标签: r plotly r-plotly

enter image description here

在上面的图中,我要固定颜色,或者美元,澳元,加元,欧元和其他主要货币可以具有随机颜色。如何实现呢?货币数量可以变化。

fit <- lm(YVal ~ `Maturity Date`, data = filtered_data(), na.action=na.exclude)

p <- plot_ly(data = filtered_data(),  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers', 
             color = ~Crncy, colors = setNames(rainbow(nrow(filtered_data())), filtered_data()$Crncy),
             marker = list(opacity = 0.7, size=12) ,
             text = ~paste(" Security: ", filtered_data()$Security, "<br>",
                           "Currency: ", filtered_data()$Crncy, "<br>",
                           "YTM: ", filtered_data()$YTM,"<br>",
                           ifelse(filtered_data()$Floater=='Y',
                                  paste("DM: ", filtered_data()$YVal), 
                                  paste("ASW (USD): ", filtered_data()$YVal))
                           , "<br>", factor(filtered_data()$Sym))
                           ) %>% 
  layout(xaxis = list(title="Maturity"), 
         yaxis = list(title="FRN: DM | Fixed: YAS ASW USD")) %>% 
  add_markers(symbol = ~factor(filtered_data()$Sym),color = I("black"), marker = list( opacity = 1, size=6)) %>% 
  add_lines(x = ~`Maturity Date`, y = fitted(fit), showlegend = FALSE)

 

1 个答案:

答案 0 :(得分:1)

类似这样的代码,它为焦点(“固定”)组设置了一个指定的向量,并为其余组附加了一个彩虹调色板(关于彩虹调色板与固定对象冲突的可能性,我没有做任何事情指定的颜色,但这应该是一个起点)

fd <- filtered_data
fixed_col <- c(USD="blue", AUD="magenta", CAD="red", EUR="black")
all_grps <- unique(fd$Currency)
nonfix_grps <- setdiff(all_grps, names(fixed_col))
n_grp <- length(all_grps)
n_fix <- length(fixed_col)

现在将固定组(第一个)和非固定组(第二个)的颜色值和名称结合起来

col_vec <- c(fixed_col, rainbow(n_grp-n_fix))
names(col_vec) <- c(names(fixed_col), nonfix_grps))