Coloring a geom_histogram by gradient

后端 未结 2 1225
甜味超标
甜味超标 2021-01-12 20:34

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 <-          


        
2条回答
  •  囚心锁ツ
    2021-01-12 21:03

    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")
    colGradient <- colorRampPalette(cols)
    cut.cols <- colGradient(bins)
    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))
    

提交回复
热议问题