James
James

Reputation: 123

How to color geom_bar by y-axis values?

I'm making a standard bar plot with ggplot2 geom_bar. I'm trying to fill the bars with the highest values with a different color than the bars with the lowest values.

For example,

ggplot(mtcars, aes(x=as.factor(cyl) )) + geom_bar()

How can you color bars above 20 in red (e.g., E), bars from 10 to 20 in blue (B and D), and bars below 10 in orange (A and C).

Thanks for any insights!

enter image description here

I'm using geom_col and my actual code looks like this

ggplot(data, aes(x=State, y=Value)) +
 geom_col()

Upvotes: 3

Views: 986

Answers (1)

markus
markus

Reputation: 26343

You might use cut

ggplot(mtcars, aes(x = as.factor(cyl))) +
  geom_bar(aes(fill = cut(stat(count), breaks = c(0, 8, 12, Inf)))) +
  labs(fill = "Breaks")

enter image description here

You obviously need to adjust the breaks according to your needs / data.


edit

If we use geom_col instead of geom_bar we need to change fill = stat(count) to fill = value_column (whatever the value_column is but it should be the same as the one we mapped to y).

Example:

df <- data.frame(trt = c("a", "b", "c"), outcome = c(2.3, 1.9, 3.2))
ggplot(df, aes(trt, outcome)) +
  geom_col(aes(fill = cut(outcome, breaks = c(0, 2, 3, Inf)))) +
  labs(fill = "Breaks")

Upvotes: 4

Related Questions