ggplot2极简入门

一、基本思想和语法框架

  • 基本思想:图形分层是关键,图形叠加+来实现
  • 基本语法框架如下:
ggplot()    +   # 基础图层,不出现图形
geom_xxx() | stat_xxx()   +   # 几何图层或统计变化,出现图形
facet_xxx()   +   # 分面系统,将某个变量进行分面交换
coord_xxx()   +   # 坐标变化,默认为笛卡尔坐标系
guides()   +   # 图例调整
theme()   +   # 主题设定
labs() +        #  图表标题和坐标轴标题
scale_xxx()  # 度量调整,调整具体的标度
  1. 其中,ggplot()+geom_xxx() | stat_xxx()是ggplot2画图的核心部分,是ggplot2图形所必需的元素;
  2. facet_xxx()coord_xxx()guides()theme()labs()scale_xxx()是ggplot2画图的美化部分,属于非必需的元素。

二、实战演习

> mpg
# A tibble: 234 x 11
   manufacturer model      displ  year   cyl trans      drv     cty   hwy fl    class  
                                
 1 audi         a4           1.8  1999     4 auto(l5)   f        18    29 p     compact
 2 audi         a4           1.8  1999     4 manual(m5) f        21    29 p     compact
 3 audi         a4           2    2008     4 manual(m6) f        20    31 p     compact
 4 audi         a4           2    2008     4 auto(av)   f        21    30 p     compact
 5 audi         a4           2.8  1999     6 auto(l5)   f        16    26 p     compact
 6 audi         a4           2.8  1999     6 manual(m5) f        18    26 p     compact
 7 audi         a4           3.1  2008     6 auto(av)   f        18    27 p     compact
 8 audi         a4 quattro   1.8  1999     4 manual(m5) 4        18    26 p     compact
 9 audi         a4 quattro   1.8  1999     4 auto(l5)   4        16    25 p     compact
10 audi         a4 quattro   2    2008     4 manual(m6) 4        20    28 p     compact
# … with 224 more rows
  • mpg数据集包含了由美国环境保护协会收集的 38 种车型的观测数据;
  • mpg数据集包括以下变量:
参数 解释
manufacturer 生产商
model 型号
displ 引擎大小,单位为升
year 制造年份
cyl 气缸数
trans 变速器
drv 驱动系统。其中,f是前轮驱动,r是后轮驱动,4是前、后驱动
cty 汽车在城市公路上行驶时的燃油效率,单位为英里 / 加仑
hwy 汽车在高速公路上行驶时的燃油效率,单位为英里 / 加仑
fl 燃油类型
class 车型
  • 下面,我们以mpg数据集为例子进行演示;

①. 创建ggplot2图形

· 创建ggplot2图形,我们需要ggplot()+geom_xxx() | stat_xxx()
· 例如:

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy))

image.png

· 假如我们只有ggplot(),没有geom_xxx() | stat_xxx()
· 我们发现只有空白图被创建

ggplot(data = mpg)

image.png

· geom_xxx()stat_xxx()很相似,大多数情况下可以产出一样的图片
· 但geom_xxx()倾向于作图,stat_xxx()倾向于统计
· 大多数情况下,ggplot()+geom_xxx()可以满足我们的需求

> ggplot(data = mpg) + geom_bar(mapping = aes(x = drv))
image.png
> ggplot(data = mpg) + stat_count(mapping = aes(x = drv))
image.png

· 与此同时,mapping是一个需要注意的参数
· 没有mapping,函数将发生报错

> ggplot(data = mpg) +  geom_point()
Error: geom_point requires the following missing aesthetics: x and y
Run `rlang::last_error()` to see where the error occurred.

· mapping就是映射。
· 除了映射基本的X轴Y轴,还可以映射colorfillalphasizelinetypeshape
· 例如,映射到color中:

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy, color = class))
image.png

· 可以指定所有点为同一颜色

ggplot(data = mpg) + geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
image.png

· 虽然数据集中有234 个观测值,但散点图中只显示了 126 个点
· 因为hwydispl的值都进行了舍入取整,所以这些点显示在一个网格上时,很多点彼此重叠了。这个问题称为过绘制。点的这种排列方式很难看出数据的聚集模式。
· 通过将位置调整方式设为“抖动”,例如position = "jitter",可以避免这种网格化排列。 为每个数据点添加一个很小的随机扰动,这样就可以将重叠的点分散开来,因为不可能有两个点会收到同样的随机扰动:

ggplot(data = mpg) +
 geom_point(
 mapping = aes(x = displ, y = hwy, color = class),
 position = "jitter"
 )
image.png

· 例如,映射到alpha中:

> ggplot(data = mpg) +  geom_point(mapping = aes(x = displ, y = hwy, alpha=displ))
image.png

· 例如,映射到'shape'中:

> ggplot(data = mpg)+ geom_point(mapping = aes(x = displ, y = hwy, shape=displ))
Error: A continuous variable can not be mapped to shape
Run `rlang::last_error()` to see where the error occurred.
> ggplot(data = mpg)+ geom_point(mapping = aes(x = displ, y = hwy, shape=drv))
image.png

· 可以指定所有点为同一形状

ggplot(data = mpg)+ geom_point(mapping = aes(x = displ, y = hwy),shape=1)
image.png
image.png

· 总结一下所有的映射参数

参数 意义
color/col/colour 点、线、和填充区域轮廓的颜色
fill 填充区域的颜色
alpha 颜色的透明度,数值范围从0(完全透明)到1(不透明)
size 点的尺寸或线的宽度,默认单位为mm
angle 角度
vjust 指垂直位置微调,在(0,1)区间的数字或位置字符串:0=‘button’,0.5=‘middle’,1=‘top’
hjust 指水平位置微调,在(0,1)区间的数字或位置字符串:0=‘left’,0.5=‘center’,1=‘right’
linetype 线条的类型,包括白线(0=‘blank’)、实线(1=‘solid’)、短虚线(2=‘dashed’)、点线(3=‘dotted’)、点横线(4=‘dotdash’)、长虚线(5=‘longdash’)、短长虚线(6=‘towdash’)
shape 点的形状,为[0,25]区间的26个整数,分别对应方形、圆形、三角形、菱形等26中不同的形状。有的形状有填充颜色(fill属性),但有的形状只有轮廓颜色(color)的属性。

· mapping可以放在ggplot() 里面,也可以放在 geom_point()里面
· 当你有多个 geom_point()时,放在ggplot() 里面是一个方便的选择
· 但当你对每个geom_point()都有不同的映射要求时,你需要在每个geom_point()单独放一个mapping

ggplot(data = mpg) +
 geom_point(mapping = aes(x = displ, y = hwy)) +
 geom_smooth(mapping = aes(x = displ, y = hwy))
image.png
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
 geom_point() +
 geom_smooth()
image.png
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv))
image.png

②.美化部分

1).构面:facet_xxx()

· 通过单个变量对图进行分面,可以使用函数 facet_wrap()
· 传递给 facet_wrap() 的变量应该是离散型

ggplot(data = mpg) +
 geom_point(mapping = aes(x = displ, y = hwy)) +
 facet_wrap(~ class, nrow = 2)

image.png

· 通过两个变量对图进行分面,需要在绘图命令中加入函数facet_grid()

ggplot(data = mpg) +
 geom_point(mapping = aes(x = displ, y = hwy)) +
 facet_grid(drv ~ cyl)
image.png

2).坐标系:coord_xxx()

· 默认的坐标系是笛卡儿直角坐标系
· coord_flip()函数可以交换 x 轴和 y 轴
· coord_polar()函数使用极坐标系

ggplot(data = mpg) +
 geom_bar(mapping = aes(x = drv,fill=drv))
image.png
ggplot(data = mpg) +
 geom_bar(mapping = aes(x = drv,fill=drv))+coord_flip()
ggplot(data = mpg) +
 geom_bar(mapping = aes(x = drv,fill=drv))+coord_polar()
image.png

3).图例:guides()

· 如果要控制图例的整体位置,你需要设置 theme()函数中的legend.position参数;

ggplot(mpg, aes(displ, hwy)) +
 geom_point(aes(color = class)) +
 geom_smooth(se = FALSE) +
 theme(legend.position = "bottom") 
image.png

· 如果想要更加精细地调整图例,请配合 guide_legend()guide_colorbar() 函数来使用guides() 函数

ggplot(mpg, aes(displ, hwy)) +
 geom_point(aes(color = class)) +
 geom_smooth(se = FALSE) +
 theme(legend.position = "bottom") +
 guides(color = guide_legend(nrow = 1,override.aes = list(size = 4))
 )
image.png

4).主题:theme()

· theme()可以定制图形中的非数据元素:例如绘图区背景、网格线、坐标轴线条、坐标轴标签、图例的位置和背景等等
· ggplot2图表的主题系统主要对象包括文本(text)矩形(rect)线条(line)三大类,对应的函数包括element_text()element_rect()element_line(),另外还有element_black()表示该对象设置为无

image.png

· 我们来试一下axis.title
· 原来的图片:

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv))
image.png

· 加上axis.title=elment_black(),我们发现x轴y轴的标题消失了

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv)) + theme(axis.title=element_blank())

image.png

· ggplot2的主题设置参数十分繁杂
· 我们建议新手先掌握theme()中这3方面的参数:(使用频率高)
· 1. 坐标轴的标签(axis.text.xaxis.text.y);
· 2. 图例的位置与背景(legend.positionlegend.background);
· 3. 默认的主题系统
· ggplot2 默认可以使用 8 种设置好的绘图区背景和网格线,分别如下:
image.png

· 没有应用theme_bw()

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv))

image.png

· 应用theme_bw()

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv)) + theme_bw()

image.png

· 背景风格发生了改变,似乎要比之前好看一点
· 我们试试换成theme_classic()

ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv)) + theme_classic()
image.png

· 好像变得更好看一点了

5).标签: labs()

· 为图形添加一个标题

ggplot(mpg, aes(displ, hwy)) + 
geom_point(aes(color = class)) + 
geom_smooth(se = FALSE) + 
labs( title = "Fuel efficiency generally decreases with engine size")

image.png

· 使用labs()函数来替换坐标轴中的标题图例中的标题

ggplot(mpg, aes(displ, hwy)) +
 geom_point(aes(color = class)) +
 geom_smooth(se = FALSE) +
 labs(
 x = "Engine displacement (L)",
 y = "Highway fuel economy (mpg)",
 colour = "Car type"
 )
image.png

6).度量:scale_xxx()

· 度量用于控制变量映射到视觉对象的具体细节,比如:X轴和Y轴的度量、alpha(透明度)、color(轮廓颜色)、fill(填充颜色)、lineshape(线条形状)、shape(形状)等,他们都有相应的度量函数。
· 根据视觉通道映射的变量属性,将度量调整函数分成数值型类别型两大类
· 需要注意的是:scale_*_manual()表示手动自定义离散的度量

image.png

· 原来的图形:

ggplot(mpg, aes(displ, hwy)) +
    geom_point(aes(size = cty),color="green") 
image.png

· 加了scale_size()限定一下点的大小

ggplot(mpg, aes(displ, hwy)) +
    geom_point(aes(size = cty),color="green") +scale_size(range = c(0.1,3))

image.png

· 加了scale_x_continuous更改X轴范围

ggplot(mpg, aes(displ, hwy)) +
    geom_point(aes(size = cty),color="green") +scale_x_continuous(limits = c(1,10))
image.png

· 原来的图形:

ggplot(mpg, aes(displ, hwy)) +
 geom_point(aes(color = drv))

image.png

· 加了scale_color_brewer()更改原来的颜色种类

ggplot(mpg, aes(displ, hwy)) +
 geom_point(aes(color = drv)) +
 scale_color_brewer(palette = "Set1")

image.png

三、保存图形的方法

· 位图矢量图的区别

  1. 通过Rstudio保存图片
    image.png
  2. 使用文件类型所对应的函数,如tiff()png()svg()pdf()
pdf("mpg.pdf")
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv)) + theme_bw()
dev.off()
  1. ggsave()函数:可以保存ggplot2包绘制的图表
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
    geom_point(mapping = aes(color = class)) +
    geom_smooth(mapping = aes(group = drv)) + theme_bw()
ggsave("mpg.pdf")

四、总结

ggplot() + # 基础图层,不出现图形
geom_xxx() | stat_xxx() + # 几何图层或统计变化,出现图形
facet_xxx() + # 分面系统,将某个变量进行分面交换
coord_xxx() + # 坐标变化,默认为笛卡尔坐标系
guides() + # 图例调整
theme() + # 主题设定
labs() + # 图表标题和坐标轴标题
scale_xxx() # 度量调整,调整具体的标度

ggplot(data = mpg) +
  geom_point(mapping = aes(x = displ, y = hwy,color = drv)) +
  facet_wrap(~ class, nrow = 2) +
  guides(color = guide_legend(nrow = 1)) +
  theme_classic() +
  labs(title = "Fuel efficiency generally decreases with engine size",
       x = "Engine displacement (L)", 
       y = "Highway fuel economy (mpg)",
       colour = "drv way") +
  theme(plot.title = element_text(hjust = 0.5)) +
  scale_x_continuous(limits = c(1,10)) +
  theme(legend.position = "bottom") 
image.png

你可能感兴趣的:(ggplot2极简入门)