更改条形图中特定条形的颜色 [英] Change colours of particular bars in a bar chart

查看:727
本文介绍了更改条形图中特定条形的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一些条形图,我想知道是否有可能在图表上根据他们是否位于x轴上方或下方的颜色条。

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 clarification, this is the type of bar-chart I mean:

理想情况下,我希望能够将条形上方的颜色与下面的颜色区分开来,吸引力,我一直在搜索,但我找不到任何方法这样做,任何人都可以帮助?

Ideally I would like to be able to colour the bars above a separate colour to those below so the graph looks more appealing, I've been searching but I can't find any method of doing this, can anyone help?

提前感谢。 :)

推荐答案

这里有一个策略:

## 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()代替简单的逻辑测试):

If you want more than two value-based colors, you can employ a similar strategy (using findInterval() in place of the simple logical test):

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" 

这篇关于更改条形图中特定条形的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆