R中条形图中不同列的单独条件着色

时间:2014-06-21 08:39:35

标签: r bar-chart

我有特定候选人的以下数据再次评估基准数据。在这里找到csv文件:

Competencies    Desired Score
DRIVE           6       6.72
CUST ORIENTATION    6   6.58
INNOVATION  6   6.43
TEAM WORK   5   6.88
ANALYTICAL THINKING 6   7
LEADERSHIP  3   6.42
ASSERTIVENESS   3   6.73
PROBLEM SOLVING 4   6.73
IMPLEMENTATION & EXECUTION  6   6.85
WORKING KNOWLEDGE   6   5
BU KNOWLEDGE    3   4.58
FU KNOWLEDGE    3   4.7
KNOWLEDGE OF THE BUSINESS ENVIRONMENT   4   4.72

我必须制作一个这样的横条图:

http://i.stack.imgur.com/jleQf.png

其中基准色谱柱的颜色固定为蓝色,分数列的颜色基于以下条件:

cols <- ifelse(import1$Score>import1$Desired,"green",
           ifelse(import1$Score>=(0.96*import1$Desired) & import1$Score<import1$Desired,
                  "yellow", "red"))

如何在条形图中执行此操作,以便barplot采用如下所述的颜色(我已手动输入):

barplot(t(as.matrix(import1[,1:2])),horiz=TRUE,
    col=c("blue","green","blue", "green","blue", "green","blue", 
          "green","blue","green","blue", "green","blue","green" ,"blue",
          "green","blue", "green","blue", "red","blue","green","blue", "green","blue", "green" ),cex.names=0.5,las=1,cex.axis=0.6,beside=TRUE,border=NA)

我想在col中使用一些基于条件的方法。

编辑: 附加查询

如果我对同一组能力有多个分数,我该如何在上述条件下制作单独的一组图表。

Competencies    Desired Score 1 Score 2 Score 3
DRIVE           6       6.72        5.2 6.6
CUST ORIENTATION    6   6.58    6   7.6
INNOVATION  6   6.43    4.2 7
TEAM WORK   5   6.88    5.4 7.8
ANALYTICAL THINKING 6   7   4.6 7
LEADERSHIP  3   6.42    5.8 7
ASSERTIVENESS   3   6.73    4.8 6.4
PROBLEM SOLVING 4   6.73    6   6.6
IMPLEMENTATION & EXECUTION  6   6.85    6.2 6
WORKING KNOWLEDGE   6   5   3.6 5.4
BU KNOWLEDGE    3   4.58    3.8 4.4
FU KNOWLEDGE    3   4.7 4   4.6
KNOWLEDGE OF THE BUSINESS ENVIRONMENT   4   4.72    4   4.8

1 个答案:

答案 0 :(得分:0)

由于您已经在cols中拥有了所需的颜色,因此您可以通过首先生成足够的"blue"值来创建所需的矢量:

blues <- rep("blue",length(cols))

然后将此向量与另一个向量组合以获得您想要的颜色:

colors <- as.vector(rbind(blues,cols)) 

之后您的情节可以通过以下方式创建:

barplot(t(as.matrix(import1[,2:3])),horiz=TRUE,
    col=colors,cex.names=0.5,las=1,cex.axis=0.6,beside=TRUE,border=NA)

修改

将所有这些组合成一个函数如下所示:

calcCols <- function(df,score) {
    cols <- ifelse(df[,score]>df$Desired,"green",
            ifelse(df[,score]>=(0.96*df$Desired) & df[,score]<df$Desired,
                   "yellow", "red"))
    blues <- rep("blue",length(cols))
    as.vector(rbind(blues,cols))                
}

之后,您可以使用以下方法创建新数据所需的三个图表:

barplot(t(as.matrix(import1[,2:3])),horiz=TRUE,
    col=calcCols(import1,"Score.1"),cex.names=0.5,las=1,cex.axis=0.6,beside=TRUE,border=NA)

barplot(t(as.matrix(import1[,2:3])),horiz=TRUE,
    col=calcCols(import1,"Score.2"),cex.names=0.5,las=1,cex.axis=0.6,beside=TRUE,border=NA)

barplot(t(as.matrix(import1[,2:3])),horiz=TRUE,
    col=calcCols(import1,"Score.3"),cex.names=0.5,las=1,cex.axis=0.6,beside=TRUE,border=NA)