How to fill histogram with color gradient?

Art picture Art · Oct 27, 2016 · Viewed 9.6k times · Source

I have a simple problem. How to plot histogram with ggplot2 with fixed binwidth and filled with rainbow colors (or any other palette)?

Lets say I have a data like that:

myData <- abs(rnorm(1000))

I want to plot histogram, using e.g. binwidth=.1. That however will cause different number of bins, depending on data:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1) 

enter image description here

If I knew number of bins (e.g. n=15) I'd use something like:

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill=rainbow(n))

But with changing number of bins I'm kind of stuck on this simple problem.

Answer

J_F picture J_F · Oct 27, 2016

If you really want the number of bins flexible, here is my little workaround:

library(ggplot2)

gg_b <- ggplot_build(
  ggplot() + geom_histogram(aes(x = myData), binwidth=.1)
)

nu_bins <- dim(gg_b$data[[1]])[1]

ggplot() + geom_histogram(aes(x = myData), binwidth=.1, fill = rainbow(nu_bins))

enter image description here