Wednesday, January 15, 2020

Custom color gradient legend for a ggplot graph

This is likely a bad idea, but....

I've been adding colors to geom_points using scale_fill_manual(), and wanted some way of adding a figure legend at the bottom to show the color scale. Here's my solution:

nColors<-100

pal <- colorRampPalette(c("red","yellow","yellow","yellow","blue"))
myPal<-rev(pal(nColors))
myColors<-character(nColors)
for (i in 1:nColors){
  myColors[i]<-myPal[i]
}

x1<-seq(1:nColors)/50
x2<-(x1+(1/50))
d<-data.frame(x1 = x1, xmax = x2, ymin = 1, ymax = 3, color = as.factor(x2))
ggplot() + geom_point(data = mpg, aes(displ, hwy)) +  geom_rect(data = d, aes(xmin=x1, xmax=xmax, ymin=ymin, ymax=ymax), fill = myColors)

And the result:


No comments:

Post a Comment

Retrieve GO terms for a gene list from pantherdb.org

Pantherdb.org has what looks like a fairly up to date and comprehensive listing of genes and gene ontologies. I recently wanted to generate ...