2

I want to create a histogram in R and ggplot2, in which the bins are filled based on their continuous x-value. Most tutorials only feature coloring by discrete values or density/count.

Following this example was able to color the bins with a rainbow scale:

df <- data.frame(x = runif(100))

ggplot(df) +
  geom_histogram(aes(x), fill = rainbow(30))

Rainbow histogram

I want to use a color gradient, where the bins are from blue (lowest) to yellow (highest). The scale_fill_gradient() function seems to achive that, yet when i insert it in place of rainbow() for the fill argument i receive an error:

> ggplot(df) +
+ geom_histogram(aes(x), fill = scale_fill_gradient(low='blue', high='yellow'))

Error: Aesthetics must be either length 1 or the same as the data (30): fill

I tried several ways to supply the length of 30 for the scale, yet i get the same error every time. So my question is:

  1. Is scale_color_gradient the right function for the fill argument or do i have to use another one?
  2. If it is the right function, how can i correctly supply the length?
Pythagyros
  • 23
  • 1
  • 4

1 Answers1

5

If you want different colors for each bin, you need to specify fill = ..x.. in the aesthetics, which is a necessary quirk of geom_histogram. Using scale_fill_gradient with your preferred color gradient then yields the following output:

ggplot(df, aes(x, fill = ..x..)) +
  geom_histogram() +
  scale_fill_gradient(low='blue', high='yellow')

enter image description here

tifu
  • 1,352
  • 6
  • 17
  • Thank you - exactly what i was looking for. I've encountered other variables like `..count..` or `..density..` before, but was unable to find how many or which there are exactly. – Pythagyros May 03 '18 at 09:10