How to set the legend of color gradient in ggplot2

2019-09-18 17:41发布

问题:

I'm trying to do a bubble chart where the colors of the points are a gradient color depending on a value. The limit values I've set are 0.0001 to 0.1. The problem i have is that i want that the legend of color gradient have the same length from 0.0001 to 0.001, from 0.001 to 0.01, and from 0.01 to 0.1. The code I've wrote represents 0.5 in the middle of scale. I have this:

x <- as.data.frame(cbind(c("rRNA modification","response to hydrogen peroxide","RNA processing","mRNA processing","rRNA modification","response to hydrogen peroxide","RNA processing","mRNA processing"),c("DE","DE","DE","DE","AS","AS","AS","AS"),c(3.42,2.78,1.37,0.83,0,2.87,4.05,8.63),c(4.62e-08,4.32e-03,9.00e-02,8.60e-01,0,5.30e-01,5.67e-03,6.72e-03)))
colnames(x) <- c("go","set_gene","factor","p.value")
x$factor<- as.numeric(as.character(x$factor))
x$p.value <- as.numeric(as.character(x$p.value))
library(ggplot2)
plot1 <- ggplot(x,aes(x=set_gene,y=go,size=factor,fill=ifelse(p.value>0.1,0.1,ifelse(p.value<0.0001,0.0001,p.value))))
plot1 <- plot1+ geom_point(shape=21,size=x$factor*4)
library(scales)
plot1<- plot1 + 
scale_fill_gradientn(colours=c("red","orange","yellow","grey90"),values = 
rescale(c(0.0001,0.001,0.01,0.1)),limits=c(0.0001,0.1))
plot1

Current result:

Desired result:

Thanks!

回答1:

How about using:

  plot1<- plot1 + scale_fill_gradientn(name = "p-value", trans = "log", breaks =  c(0.0001,0.001,0.01,0.1),limits = c(0.0001,0.1),colours=c("red","orange","yellow","grey90"))

Output: