如何在R中应用颜色查找表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在R中应用颜色查找表相关的知识,希望对你有一定的参考价值。
对于涉及运动队的数据,我想为我生成的任何图表从查找表中应用一致的自定义颜色。这是我目前的工作
library(tidyverse)
library(plotly)
lookup <- tibble(team=c("Dolphins","Sharks","Minnows"), color_id =c("dodgerblue","red","black"))
data <- tibble(team =c("Dolphins","Sharks","Minnows","Sharks"),V1=c(1:4),V2=c(4:1))
df <- data %>%
left_join(lookup)
colors <- lookup$color_id
plot_ly(df, x= ~ V1, y= ~ V2, color = ~ color_id, name = ~ team, colors = colors)
如您所见,图例无法正确识别颜色。例如,海豚应该是dodgerblue
提前感谢
答案
[这似乎是一个古怪,从总体上来说并不像预期的那样。
您已经在初始数据框中定义了颜色,因此有两个可能的选项似乎与所需的解决方案很接近。I()用于指定变量为身份(即,按原样使用此值,并且不解释为因素)
library(plotly)
df <- structure(list(team = c("Dolphins", "Sharks", "Minnows", "Sharks"
), V1 = 1:4, V2 = 4:1, color_id = c("dodgerblue", "red", "black",
"red")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
))
colors <- lookup$color_id
#original
plot_ly(df, x= ~ V1, y= ~ V2, color = ~ color_id, name = ~ team, colors = colors) #wrong order, 1 different color
这里您想由可变团队使用“颜色”为调色板指定颜色。
#this works but color palette needs to the same order as the teams
plot_ly(df, x= ~ V1, y= ~ V2, color = ~team, name = ~ team, size=I(70),
colors = c("dodgerblue", "black", "red") )
第二个选项是使用所需调色板的向量直接指定颜色选项。
#This should work, but is not using the desired colors
plot_ly(df, x= ~ V1, y= ~ V2, color = I(~color_id), name = ~ team, size=I(50))
#If we manually specify the desired colors by directly referencing the data frame it works:
plot_ly(df, x= ~ V1, y= ~ V2, color = I(df$color_id), name = ~ team, size=I(50))
以上是关于如何在R中应用颜色查找表的主要内容,如果未能解决你的问题,请参考以下文章