首页 > 解决方案 > 将颜色分配给从 DF 中选择相应颜色的标志

问题描述

我想在我的情节中C为特定的标志 ( ) 分配特定的颜色 ( ) 。POP我试过

PC <- data.frame(POP = c("A", "C", "C", "B"), 
                 X = c(0.1,0.2,0.3,0.4), 
                 Y = c(0.1,0.2,0.3,0.4))

COLS <- data.frame(C = c("red", "grey", "brown"), 
                   P = c("A", "B","C"))

plot(PC$X, PC$Y, col = COLS$C[which(COLS$P == PC$POP)])

但得到以下错误

 Warning messages:
  1: In `==.default`(COLS$P, PC$POP): longer object length is not a multiple of shorter object length
  2: In is.na(e1) | is.na(e2): longer object length is not a multiple of shorter object length

结果图中的颜色不正确。

标签: rdataframeplot

解决方案


代替col = COLS$C[match(PC$POP, COLS$P)]。看?match它的用途。

您不能安全地应用于"=="两个不同长度的向量。逻辑与添加两个不同长度的向量相同。适用回收规则。此规则在某些应用程序中很有用,但您有责任让它做正确的事情/产生所需的结果。

此外,您需要调用stringsAsFactors = FALSEdata.frame()避免将颜色变量(字符串)编码为因子(整数)。


推荐阅读