VFreguglia
VFreguglia

Reputation: 2311

Bar color according to height in ggplot2

How can I change the color of bars in a bar-chart to be in a scale according to its height? Here's an example:

library(ggplot2)
year = c(2000,2000,2001,2001,2001,2002,2003,2003,2004,2004,2004,2004,2005)
df = data.frame(year)

ggplot(df) + geom_bar(aes(year,fill=year))

I need the colors to be in a scale according to the count of each year (light blue for years with a low counts and dark blue for higher counts, for example).

I could do it by using the counts as the data frame (2000;2, 2001;3, etc.), but that would require a lot of work in other parts of my code, so I'd rather keep the data in this format.

Upvotes: 2

Views: 1932

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98429

Use the ..count.. computed by ggplot() function as your fill variable.

ggplot(df) + geom_bar(aes(year,fill=..count..))

Upvotes: 5

Related Questions