我一直在创建一些条形图,我想知道是否可以根据它们位于 x 轴上方或下方来为图表上的条形着色?
为了澄清起见,这是我的意思的条形图类型:
理想情况下,我希望能够将上面的条形与下面的单独颜色着色,这样图表看起来更有吸引力,我一直在搜索,但找不到任何方法,有人可以帮忙吗?
提前致谢。:)
这是一种策略:
## 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"
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')
scale_fill_discrete(guide = 'none')
removes the legend, position = 'dodge'
stops the warning that comes from the default position = 'stack'
.
一种方法是使用逻辑变量或因子变量来索引颜色向量(这是 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
1
s 和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
。
结果图应如下所示
我在寻找有关如何根据因素为条形图中的各个条形着色的帮助时找到了此页面。我找不到任何其他信息来源,但多亏了这个页面,我想出了这个:
cols <- ifelse(df$Country == "格陵兰", "green","blue")
然后它以如上所述的通常方式传递到 barplot 中:
条形图(x,col = cols)