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?
Thanks in advance. :)
On a chart, select the individual data marker that you want to change. On the Format tab, in the Shape Styles group, click Shape Fill. Do one of the following: To use a different fill color, under Theme Colors or Standard Colors, click the color that you want to use.
Select a data series. Click Color . Pick an option to set the color of the bars. Select Left axis or Right axis to move the axis labels.
Use the Chart Styles button to quickly change the color or style of the chart. Click the chart you want to change. In the upper-right corner, next to the chart, click Chart Styles. Click Color and pick the color scheme you want, or click Style and pick the option you want.
a) Click on the bars to select them, then go to the Chart Styles group under the Design tab and select the relevant color style from the gallery. b) Click on individual bars to select them, then go the Shape Styles group under the Format tab and select a color from the Shape Fill button.
Here's one strategy:
## 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)
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"
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With