跳到正文
0%

ggplot2科研绘图

ggplot2基本要素

  • 数据(Data)和映射(Mapping)
  • 几何对象(Geometric)
  • 标尺(Scale)
  • 统计变换(Statistics)
  • 坐标系统(Coordinante)
  • 图层(Layer)
  • 分面(Facet)
  • 主题(Theme)

这里将从这些基本要素对ggplot2进行介绍。

数据(Data)和映射(Mapping)

下面以一份钻石的数据为例,这份数据非常大,随机取一个子集来画图。

> require(ggplot2)
载入需要的程辑包:ggplot2
> data("diamonds")

#sample基本用法
参数解释:x表示所要抽样数据,size表示抽样个数,replace为T表示采取有重复的抽样 , sample(nrow(),1000)表示抽取1000行,如果不加上nrow的话表示按列抽取

> small <- diamonds[sample(nrow(diamonds),1000),]
> head(small)

 A tibble: 6 x 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  1.03 Premium   E     SI2      61.8    59  4845  6.47  6.42  3.98
2  0.56 Premium   D     SI1      61.9    58  1723  5.27  5.33  3.28
3  0.65 Premium   E     SI2      61.4    59  1640  5.57  5.52  3.41
4  0.41 Very Good F     VS1      60.7    56  1007  4.77  4.82  2.91
5  0.53 Ideal     F     VS1      61.5    56  1624  5.21  5.25  3.22
6  0.55 Ideal     G     VVS1     61.2    56  2077  5.27  5.3   3.24
> summary(small)
     carat               cut      color      clarity        depth           table      
 Min.   :0.2300   Fair     : 37   D:132   SI1    :243   Min.   :55.20   Min.   :51.00  
 1st Qu.:0.3900   Good     : 89   E:181   VS2    :210   1st Qu.:61.10   1st Qu.:56.00  
 Median :0.7100   Very Good:228   F:174   SI2    :176   Median :61.90   Median :57.00  
 Mean   :0.8085   Premium  :258   G:202   VS1    :152   Mean   :61.81   Mean   :57.47  
 3rd Qu.:1.0400   Ideal    :388   H:155   VVS2   : 86   3rd Qu.:62.60   3rd Qu.:59.00  
 Max.   :5.0100                   I:108   VVS1   : 74   Max.   :70.20   Max.   :67.00  
                                  J: 48   (Other): 59                                  
     price               x                y                z        
 Min.   :  367.0   Min.   : 3.920   Min.   : 3.960   Min.   :2.380  
 1st Qu.:  932.8   1st Qu.: 4.690   1st Qu.: 4.700   1st Qu.:2.900  
 Median : 2586.5   Median : 5.730   Median : 5.735   Median :3.545  
 Mean   : 3973.2   Mean   : 5.747   Mean   : 5.745   Mean   :3.552  
 3rd Qu.: 5458.8   3rd Qu.: 6.543   3rd Qu.: 6.530   3rd Qu.:4.040  
 Max.   :18741.0   Max.   :10.740   Max.   :10.540   Max.   :6.980 

将数据映射,即将数据通过映射到图形上,比如这里以克拉(carat)数为X轴变量,价格(price)为Y轴变量

> p <- ggplot(data=small,mapping=aes(x=carat,y=price))

然后告诉ggplot2需要绘制什么样类型的图形

> p + geom_point()

Rplot13.png

几何对象将在下面的小节介绍,这一节,关注的是数据和图形属性之间的映射。

如果想将切工(cut)映射到形状属性。只需要:

p <- ggplot(data=small,mapping = aes(x=carat,y=price,shape=cut))
p + geom_point()
Warning message:
Using shapes for an ordinal variable is not advised 

Rplot.png

通过点的形状来进行分组还不够的话,以及对其添加对应的颜色

几何对象(Geometric)

在上面的例子中,各种属性映射由ggplot函数执行,只需要加一个图层,使用geom_point()告诉ggplot要画散点,于是所有的属性都映射到散点上。

geom_point()完成的就是几何对象的映射,ggplot2提供了各种几何对象映射,如geom_histogram用于直方图,geom_bar用于画柱状图,geom_boxplot用于画箱式图等等。

不同的几何对象,要求的属性会有些不同,这些属性也可以在几何对象映射时提供,比如上一图,也可以用以下语法来画:

p <- ggplot(small)
p+geom_point(aes(x=carat, y=price, shape=cut, colour=color))

效果如下:

ggplot2支持图层,我通常把不同的图层中共用的映射提供给ggplot函数,而某一几何对象才需要的映射参数提供给geom_xxx函数。

这一小节我们来看一下各种常用的几何对象。

直方图

直方图最容易,提供一个x变量,画出数据的分布。

> ggplot(data=small) + geom_histogram(aes(x=price))

`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

将切工映射到直方图的颜色

> ggplot(data=small) + 
geom_histogram(aes(x=price,fill=cut))

`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Rplot04.png

ggplot(small)+geom_bar(aes(x=clarity))

柱状图非常适合于画分类变量。在这里以透明度(clarity)变量为例。
按照不同透明度的钻石的数目画柱状图。

Rplot05.png

柱状图的两个要素,一个是分类变量,一个是分类变量的数目,即柱子高度

直方图一般用来描述等距数据或等比数据;柱形图一般用来描述称名数据或顺序数据。 直观上,直方图矩形之间是衔接在一起的,表示数据间的数学关系;柱形图则留有空隙,表示仅作为两个或多个不同的类,而不具有数学相关性质。

密度函数图

说到直方图,就不得不说密度函数图,数据和映射和直方图是一样的,唯一不同的是几何对象,geom_histogram告诉ggplot要画直方图,而geom_density则说我们要画密度函数图,在我们熟悉前面语法的情况下,很容易画出:

ggplot(small) + geom_density(aes(x=price,color=cut))

Rplot11.png

也可以按照分类变量进行填充

> ggplot(small) + geom_density(aes(x=price,fill=clarity))

Rplot01.png

note: 对于用 ggplot 画图而言,colour参数是指定曲线的颜色,而对于fill是对图形进行填充

箱式图

数据量比较大的时候,用直方图和密度函数图是表示数据分布的好方法,而在数据量较少的时候,比如很多的生物实验,很多时候大家都是使用柱状图+errorbar的形式来表示,不过这种方法的信息量非常低,这种情况推荐使用boxplot。

> ggplot(small) + geom_boxplot(aes(x=cut, y=price, fill=cut))

Rplot.png

或者也可以按照切工(cut)进行分类,然后对价格(price)画箱线图,然后再用colour进行分类填充

Rplot01.png

标尺(Scale)

前面我们已经看到了,画图就是在做映射,不管是映射到不同的几何对象上,还是映射各种图形属性。这一小节介绍标尺,在对图形属性进行映射之后,使用标尺可以控制这些属性的显示方式,比如坐标刻度,可能通过标尺,将坐标进行对数变换;比如颜色属性,也可以通过标尺,进行改变。

比如可以通过添加scale_clolur_manual()参数来定义图形的颜色

ggplot(small)+geom_point(aes(x=carat, y=price, shape=cut, colour=color))+scale_colour_manual(values=rainbow(7))

Rplot.png

另外也可以通过scale参数来改变Y轴的坐标尺度,如也可以额外再添加一个scale_y_log10()参数

ggplot(small)+geom_point(aes(x=carat, y=price, shape=cut, colour=color))+scale_y_log10()+scale_colour_manual(values=rainbow(7))

加完之后的图形就会变成下面的形式

Rplot.png

统计变换(Statistics)

统计变换对原始数据进行某种计算,然后在图上表示出来,例如对散点图上加一条回归线。

Rplot02.png

由于这次主要是对其进行线性回归,于是就不采用按照cut进行颜色分类什么的了,这样的话会使得整个图形比较乱,如果还是想通过不同颜色进行分类展示的话,建议可以分成不同的面板展示,后期会介绍。

这里,aes所提供的参数,就通过ggplot提供,而不是提供给geom_point,因为ggplot里的参数,相当于全局变量,geom_point()和stat_smooth()都知道x,y的映射,如果只提供给geom_point(),则相当于是局部变量,geom_point知道这种映射,而stat_smooth不知道,当然你再给stat_smooth也提供x,y的映射,不过共用的映射,还是提供给ggplot好。

ggplot2提供了多种统计变换方式:

stat_abline       stat_contour      stat_identity     stat_summary
stat_bin          stat_density      stat_qq           stat_summary2d
stat_bin2d        stat_density2d    stat_quantile     stat_summary_hex
stat_bindot       stat_ecdf         stat_smooth       stat_unique
stat_binhex       stat_function     stat_spoke        stat_vline
stat_boxplot      stat_hline        stat_sum          stat_ydensity

统计变换是非常重要的功能,我们可以自己写函数,基于原始数据做某种计算,并在图上表现出来。

坐标系统(Coordinante)

坐标系统控制坐标轴,可以进行变换,例如XY轴翻转,极坐标转换等以满足我们的各种需求。

如坐标轴翻转由coord_flip()实现

> ggplot(small,aes(x=cut,fill=cut)) + geom_bar() + scale_fill_manual(values = rainbow(5)) + coord_flip()

Rplot03.png

而转换成极坐标可以由coord_polar()实现:

> ggplot(small,aes(x=cut,fill=cut)) + geom_bar() + scale_fill_manual(values = rainbow(5)) + coord_polar()

Rplot.png

如果直接添加的就是下面的这种形状,因为coord_polar()作用是把把笛卡尔坐标变换为极坐标。该函数有theta,start,direction三个参数,后者顶多是图的微调,需要了解可以查看帮助文件,theta才是关键。极坐标参数theta有两个指标半径和角度,就饼图而言,各部分内容的角度不同,半径相同;而默认theta=”x”,即将x映射为角度,剩下的y映射为半径。

当然也可以自己设置theta=”y”, 即将y映射为角度,剩下的x为映射为半径

> ggplot(small,aes(x=cut,fill=cut)) + geom_bar() + scale_fill_manual(values = rainbow(5)) + coord_polar(theta = "y")

Rplot01.png

另外还有一种图形的表现形式是将其变成等半径的饼图形式

> ggplot(small,aes(x=factor(1),fill=cut)) + geom_bar() + scale_fill_manual(values = rainbow(5)) + coord_polar(theta="y")

Rplot02.png

饼图实际上就是柱状图,只不过是使用极坐标而已,柱状图的高度,对应于饼图的弧度。

分面(Facet)

分面可以让我们按照分类条件,对其进行分组,然后各自进行画图
需要额外添加个facet_wrap(~cut)这个参数

> ggplot(data=small,aes(x=carat,y=price)) + geom_point(aes(colour=cut)) + scale_y_log10() + scale_color_manual(values = rainbow(5)) + stat_smooth() + facet_wrap(~cut)


`geom_smooth()` using method = 'loess' and formula 'y ~ x'

Rplot12.png

主题(Theme)

通过ggplot画图之后,我们可能还需要对图进行定制,像title, xlab, ylab这些高频需要用到的,自不用说,ggplot2提供了ggtitle(), xlab()和ylab()来实现。 比如:

Rplot01.png

如果需要将标题置中的话,需要再添加theme(plot.title = element_text(hjust = 0.5))这个参数

ggplot(small,aes(cut,price,fill=cut)) + geom_boxplot() + xlab("CUT") + ylab("RPICE") + ggtitle(subtitle  = "price vs cut",label = "TEST") + theme(plot.title = element_text(hjust = 0.5))

Rplot01.png

虽然可以通过xlab()之类的参数进行,但是仍然远不能满足需求

我们需要改变字体,字体大小,坐标轴,背景等各种元素,这需要通过theme()函数来完成。

ggplot2提供一些已经写好的主题,比如theme_grey()为默认主题,我经常用的theme_bw()为白色背景的主题,还有theme_classic()主题,和R的基础画图函数较像。

别外ggthemes包提供了一些主题可供使用,包括:

theme_economist theme_economist_white
theme_wsj       theme_excel
theme_few       theme_foundation
theme_igray     theme_solarized
theme_stata     theme_tufte

示例:用的是theme_classic()参数

> require(ggthemes)
载入需要的程辑包:ggthemes
> ggplot(small,aes(cut,price,fill=cut)) + geom_boxplot() + xlab("CUT") + ylab("RPICE") + ggtitle(label = "TEST") + theme_classic() + theme(plot.title = element_text(hjust = 0.5))

Rplot03.png

最后以生物界中常用的柱状图+误差图为实例,展示ggplot2非常灵活的图层。这个实例展示了图层,标尺,主题,注释和各种细节微调多种元素。

> Normal <- c(0.83, 0.79, 0.99, 0.69)
> Cancer <- c(0.56, 0.56, 0.64, 0.52)
> m <- c(mean(Normal),mean(Cancer))
> d <- data.frame(V=c("Normal","Cancer"),mean=m,sd=s)
> d
       V  mean         sd
1 Normal 0.825 0.12476645
2 Cancer 0.570 0.05033223

#将数据框里面的Normal和Cancer转变成两个因子(factor)
> d$V <- factor(d$V,levels = c("Normal","Cancer"))

#转变成因子之后也可以再确认一下
> attributes(d$V)
$levels
[1] "Normal" "Cancer"

$class
[1] "factor"

接下来通过ggplot2进行作图

> p <- ggplot(d,aes(x=V,y=mean,fill=V,width=0.5))
#绘制误差线
> p <- p + geom_errorbar(aes(ymin=mean,ymax=mean+sd,width=.2),position = position_dodge(width = .8))

这里geom_errorbar()的position参数用了position_dodge()函数说明两个条形之间的距离。 geom_errorbar()的width参数是条形端线的宽度, 如果width=0就没有了端线。

> p <- p + geom_bar(stat="identity", position=position_dodge(width=.8), colour="black")
> p <- p + scale_fill_manual(values=c("grey80", "white"))
> p <- p + theme_bw() +theme(legend.position="none") + xlab("") + ylab("")

使用geom_bar()函数绘制条形图,条形图的高度通常表示两种情况之一:每组中的数据的个数,或数据框中列的值,高度表示的含义是由geom_bar()函数的参数stat决定的,stat在geom_bar()函数中有两个有效值:count和identity。默认情况下,stat=”count”,这意味着每个条的高度等于每组中的数据的个数,并且,它与映射到y的图形属性不相容,所以,当设置stat=”count”时,不能设置映射函数aes()中的y参数。如果设置stat=”identity”,这意味着条形的高度表示数据数据的值,而数据的值是由aes()函数的y参数决定的,就是说,把值映射到y,所以,当设置stat=”identity”时,必须设置映射函数中的y参数,把它映射到数值变量。

geom_bar()函数的定义是:

geom_bar(mapping = NULL, data = NULL, stat = “count”, width=0.9, position=”stack”)

参数注释:

  • stat:设置统计方法,有效值是count(默认值) 和 identity,其中,count表示条形的高度是变量的数量,identity表示条形的高度是变量的值;
  • position:位置调整,有效值是stack、dodge和fill,默认值是stack(堆叠),是指两个条形图堆叠摆放,dodge是指两个条形图并行摆放,fill是指按照比例来堆叠条形图,每个条形图的高度都相等,但是高度表示的数量是不尽相同的。
  • width:条形图的宽度,是个比值,默认值是0.9
  • color:条形图的线条颜色
  • fill:条形图的填充色

关于stat参数,有三个有效值,分别是count、identity和bin:

  • count是对离散的数据进行计数,计数的结果用一个特殊的变量..count.. 来表示,
  • bin是对连续变量进行统计转换,转换的结果使用变量..density..来表示
  • 而identity是直接引用数据集中变量的值
#对x及y轴进行加粗
p <- p + theme(axis.text.x = element_text(face="bold", size=12), 
               axis.text.y = element_text(face="bold", size=12))
#设置坐标原点为(0,0),并且调整纵坐标的刻度线的间距为0.2一刻度,且是从0到1.2
p <- p+scale_y_continuous(expand=c(0,0), limits=c(0, 1.2), breaks=seq(0, 1.2, by=.2))

绘制表示显著性的线条

p <- p+geom_segment(aes(x=1, y=.98, xend=1, yend=1.1))
p <- p+geom_segment(aes(x=2, y=.65, xend=2, yend=1.1))
p <- p+geom_segment(aes(x=1, y=1.1, xend=2, yend=1.1))
p <- p + annotate("text", x=1.5, y=1.08, label="*")
print(p)

最终的形成的图形

Rplot06.png

重新总结一下上面的R代码

Normal <- c(0.83, 0.79, 0.99, 0.69)
Cancer <- c(0.56, 0.56, 0.64, 0.52)
m <- c(mean(Normal), mean(Cancer))
s <- c(sd(Normal), sd(Cancer))
d <- data.frame(V=c("Normal", "Cancer"), mean=m, sd=s)
d$V <- factor(d$V, levels=c("Normal", "Cancer"))

p <- ggplot(d, aes(V, mean, fill=V, width=.5))
p <- p+geom_errorbar(aes(ymin=mean, ymax=mean+sd, width=.2), 
                     position=position_dodge(width=.8))
p <- p + geom_bar(stat="identity", position=position_dodge(width=.8), colour="black")
p <- p + scale_fill_manual(values=c("grey80", "white"))
p <- p + theme_bw() +theme(legend.position="none") + xlab("") + ylab("")
p <- p + theme(axis.text.x = element_text(face="bold", size=12), 
               axis.text.y = element_text(face="bold", size=12))
p <- p+scale_y_continuous(expand=c(0,0), limits=c(0, 1.2), breaks=seq(0, 1.2, by=.2))
p <- p+geom_segment(aes(x=1, y=.98, xend=1, yend=1.1))
p <- p+geom_segment(aes(x=2, y=.65, xend=2, yend=1.1))
p <- p+geom_segment(aes(x=1, y=1.1, xend=2, yend=1.1))
p <- p + annotate("text", x=1.5, y=1.08, label="*")
print(p)

资料参考:
https://guangchuangyu.github.io/statistics_notes/ggplot2.html#section-3.11
https://www.cnblogs.com/ljhdo/p/5555858.html
https://shixiangwang.github.io/home/cn/post/
https://cloud.tencent.com/developer/article/1593274
https://www.jianshu.com/p/aa9154786dd2

围绕这篇笔记交流

公开反馈按文章归档,滚动到这里后加载。

在 GitHub 查看反馈