Change colours of particular bars in a bar chart

后端 未结 4 1148
轮回少年
轮回少年 2020-12-01 04:47

I\'ve been creating some bar-charts and I was wondering is it possible to colour bars on a chart depending on whether they lie above or below the x-axis?

For clarifi

4条回答
  •  醉梦人生
    2020-12-01 05:18

    One way is to index a vector of colours with a logical or factor variable (this is a common idiom in R.

    set.seed(1)
    NAO <- rnorm(40)
    cols <- c("red","black")
    pos <- NAO >= 0
    barplot(NAO, col = cols[pos + 1], border = cols[pos + 1])
    

    The trick here is pos:

    > pos
     [1] FALSE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE
    [11]  TRUE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
    [21]  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE
    [31]  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE
    

    which we coerce to numeric in the barplot() call:

    > pos + 1
     [1] 1 2 1 2 2 1 2 2 2 1 2 2 1 1 2 1 1 2 2 2 2 2 2 1 2 1 1 1 1 2
    [31] 2 1 2 1 1 1 1 1 2 2
    

    The vector of 1s and 2s selects elements from the vector of colour cols, such that:

    > cols[pos + 1]
     [1] "red"   "black" "red"   "black" "black" "red"   "black"
     [8] "black" "black" "red"   "black" "black" "red"   "red"  
    [15] "black" "red"   "red"   "black" "black" "black" "black"
    [22] "black" "black" "red"   "black" "red"   "red"   "red"  
    [29] "red"   "black" "black" "red"   "black" "red"   "red"  
    [36] "red"   "red"   "red"   "black" "black"
    

    which is the colour passed on to each bar drawn.

    In the code above I also set the border of the bars to the relevant colour, via argument border.

    The resulting plot should look like this

    enter image description here

提交回复
热议问题