Coloring geotags with a gradient

I am trying to plot a geom_histogram where the stripes are colored with a gradient.

This is what I am trying to do:

library(ggplot2)
set.seed(1)
df <- data.frame(id=paste("ID",1:1000,sep="."),val=rnorm(1000),stringsAsFactors=F)
ggplot(df,aes_string(x="val",y="..count..+1",fill="val"))+geom_histogram(binwidth=1,pad=TRUE)+scale_y_log10()+scale_fill_gradient2("val",low="darkblue",high="darkred")

      

But getting: enter image description here

Any idea how to make it paint a specific gradient?

+3


source to share


2 answers


Not sure what you can fill val

, because each row of the histogram is a set of points.

However, you can fill categorical cells with cut

. For example:



ggplot(df, aes(val, fill = cut(val, 100))) +
  geom_histogram(show.legend = FALSE)

      

histogram

+9


source


Just for completeness.

If the colors that I would like to include so that this gradient is manually selected, 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))

      

enter image description here

+1


source







All Articles