通常ggplot2默认的颜色已经比较好看了,但是为了更加自由,还是有必要学会自己如何调色。ggplot中控制颜色的函数为scale\_colour\_xxx或者scale\_fill\_xxx的形式,其实是大同小异,下面以scale\_color\_xxx为例进行讲解。

离散型变量

  • scale_color_hue
  • scale_color_discrete # scale_color_hue的别名函数
  • scale_color_brewer
  • p+scale_colour_grey
1
2
3
4
5
6
7
8
library(ggplot2)
library(gridExtra)
set.seed(200)
df<-diamonds[sample(nrow(diamonds),5000),]
p<-ggplot(data=df,aes(carat,price))+geom_point(aes(colour=cut))+theme(legend.position='none')
p1<-p+scale_color_hue(h=c(50,300),c=80,l=80)
p2<-p+scale_color_discrete(h=c(50,300),c=80,l=80)
p3<-p+scale_color_brewer(palette = 1)

1
2
3
4
p1<-p+scale_colour_grey()
p2<-p+scale_colour_grey(start = .1,end = .6)
p3<-p+scale_colour_manual(values = 2:6)
p4<-p+scale_colour_manual(values = c('orange','red','blue','green','purple'))

连续性变量

1
2
3
4
p<-ggplot(data=df,aes(carat,price))+geom_point(aes(colour=table))
p1<-p+scale_color_gradient(low='green',high='red')
p2<-p+scale_color_gradientn(colours = 2:6)
p3<-p+scale_color_gradient2(low = 'white',mid='green',high = 'red',limits=c(-20,120))

修改图例

1
2
3
4
5
6
7
8
9
10
11
12
p1<-ggplot(data=df,aes(carat,price))+
geom_point(aes(colour=cut))+
scale_colour_manual(values = 2:6)
p2<-ggplot(data=df,aes(carat,price))+
geom_point(aes(colour=cut))+
scale_colour_manual(values = 2:6,label=c('Good'='G' , 'Fair'='F','Very Good'='V','Premium'='P','Ideal'='I'),limits=c('Good','Very Good','Fair','Premium','Ideal'))
p3<-ggplot(data=df,aes(carat,price))+
geom_point(aes(colour=table))+
scale_color_gradient(low='green',high='red')
p4<-ggplot(data=df,aes(carat,price))+
geom_point(aes(colour=table))+
scale_color_gradient(low='green',high='red',limits=c(50,100),breaks=seq(50,100,25),labels=c('test1','test2','test3'))