19

我一直在创建一些条形图,我想知道是否可以根据它们位于 x 轴上方或下方来为图表上的条形着色?

为了澄清起见,这是我的意思的条形图类型:

在此处输入图像描述

理想情况下,我希望能够将上面的条形与下面的单独颜色着色,这样图表看起来更有吸引力,我一直在搜索,但找不到任何方法,有人可以帮忙吗?

提前致谢。:)

4

4 回答 4

34

这是一种策略:

## Create a reproducible example
set.seed(5)
x <- cumsum(rnorm(50))

## Create a vector of colors selected based on whether x is <0 or >0  
## (FALSE + 1 -> 1 -> "blue";    TRUE + 1 -> 2 -> "red")
cols <- c("blue", "red")[(x > 0) + 1]  

## Pass the colors in to barplot()   
barplot(x, col = cols)

如果您想要两种以上的基于值的颜色,您可以采用类似的策略(使用findInterval()代替简单的逻辑测试):

vals <- -4:4
breaks <- c(-Inf, -2, 2, Inf)
c("blue", "grey", "red")[findInterval(vals, vec=breaks)]
# [1] "blue" "blue" "grey" "grey" "grey" "grey" "red"  "red"  "red" 

在此处输入图像描述

于 2012-10-28T21:06:00.083 回答
20

A ggplot2 solution using geom_bar with stat_identity.

library(ggplot2)
ggplot(dat, aes(x= seq_along(x), y = x)) + 
  geom_bar(stat = 'identity', aes(fill = x>0), position = 'dodge', col = 'transparent') + 
  theme_bw() + scale_fill_discrete(guide = 'none') + 
  labs(x = '', y = 'NAO Index')

enter image description here

scale_fill_discrete(guide = 'none') removes the legend, position = 'dodge' stops the warning that comes from the default position = 'stack'.

于 2012-10-28T23:09:28.060 回答
15

一种方法是使用逻辑变量或因子变量来索引颜色向量(这是 R.

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

这里的诀窍是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

我们在调用中强制转换为数字 barplot()

> 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

1s 和s 的向量2从 color 的向量中选择元素cols,这样:

> 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"

这是传递给每个绘制的条的颜色。

在上面的代码中,我还通过参数将条形的边框设置为相关颜色border

结果图应如下所示

在此处输入图像描述

于 2012-10-28T21:10:32.017 回答
3

我在寻找有关如何根据因素为条形图中的各个条形着色的帮助时找到了此页面。我找不到任何其他信息来源,但多亏了这个页面,我想出了这个:

cols <- ifelse(df$Country == "格陵兰", "green","blue")

然后它以如上所述的通常方式传递到 barplot 中:

条形图(x,col = cols)

于 2016-07-18T11:08:31.897 回答