# Coloring a geom_histogram by gradient

I'm trying to plot a geom_histogram where the bars are colored by a gradient.

This is what I'm trying to do:

``````library(ggplot2)
set.seed(1)
df <- data.frame(id=paste("ID",1:1000,sep="."),val=rnorm(1000),stringsAsFactors=F)
``````

Any idea how to get it colored by the defined gradient?

Not sure you can fill by `val` because each bar of the histogram represents a collection of points.

You can, however, fill by categorical bins using `cut`. For example:

``````ggplot(df, aes(val, fill = cut(val, 100))) +
geom_histogram(show.legend = FALSE)
`````` • Just for completeness, you can use `factor(val)` instead of `cut`, but this literally turns almost every point into a unique factor level, with a unique colour, and takes a lot of time to process. Instead, to change the granularity of the gradient, better to tweak the number of cuts (which is set to 100 in this answer) May 5, 2017 at 6:35

Just for completeness.

If the colors I'd like to have the gradient on to be manually selected here's what I suggest:

data:

``````library(ggplot2)
set.seed(1)
df <- data.frame(id=paste("ID",1:1000,sep="."),val=rnorm(1000),stringsAsFactors=F)
``````

colors:

``````bins <- 10
cols <- c("darkblue","darkred")
cuts <- cut(df\$val,bins)
names(cuts) <- sapply(cuts,function(t) cut.cols[which(as.character(t) == levels(cuts))])
``````

plot:

``````ggplot(df,aes(val,fill=cut(val,bins))) +
geom_histogram(show.legend=FALSE) +
scale_color_manual(values=cut.cols,labels=levels(cuts)) +
scale_fill_manual(values=cut.cols,labels=levels(cuts))
`````` Instead of binning manually another option would be to make use of the bins computed by `stat_bin` by mapping `..x..` (or `factor(..x..)` in case of a discrete scale) or `after_stat(x)` on the `fill` aesthetic.

An issue with computing the bins manually is that we end up with multiple groups per bin for which the count has to be computed (even if the count is zero most of the time) and which get stacked on top of each other in the histogram. Especially, this gets problematic if one would add labels of counts to the histogram as can be seen in this post, because in that case one ends up with multiple labels per bin.

``````library(ggplot2)

set.seed(1)

df <- data.frame(id = paste("ID", 1:1000, sep = "."), val = rnorm(1000), stringsAsFactors = F)

ggplot(df, aes(x = val, y = ..count.. + 1, fill = ..x..)) +
geom_histogram(binwidth = .1, pad = TRUE) +
scale_y_log10() +
scale_fill_gradient2(name = "val", low = "darkblue", high = "darkred")
#> Warning: Duplicated aesthetics after name standardisation: pad
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.5968523,"math_prob":0.98106825,"size":444,"snap":"2022-27-2022-33","text_gpt3_token_len":135,"char_repetition_ratio":0.09772728,"word_repetition_ratio":0.0,"special_character_ratio":0.3063063,"punctuation_ratio":0.22340426,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9944431,"pos_list":[0,1,2,3,4,5,6],"im_url_duplicate_count":[null,2,null,2,null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-06-25T08:58:31Z\",\"WARC-Record-ID\":\"<urn:uuid:284d04fa-2bee-499e-9d2b-eed1437856d0>\",\"Content-Length\":\"245992\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:9b1f82c0-23e7-4ba1-b1f1-c8c01a4aee8c>\",\"WARC-Concurrent-To\":\"<urn:uuid:0a394cd4-f5da-456d-ae6e-b328f82efb81>\",\"WARC-IP-Address\":\"151.101.65.69\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/43795211/coloring-a-geom-histogram-by-gradient/43795338\",\"WARC-Payload-Digest\":\"sha1:LDE77QE6PENLKQCCVNH535FCMHMP6O6A\",\"WARC-Block-Digest\":\"sha1:KUZMSI6WR2E5I6G6XTGAJLNPF35J2CV7\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656103034877.9_warc_CC-MAIN-20220625065404-20220625095404-00794.warc.gz\"}"}