本章介绍ggplot2的用法。请先安装和加载包:tidyverse。
1 ggplot2概况
1.1 三个关键要素
data 数据集
aesthetic mapping 美学映射(图形的坐标系、颜色、形状等)
layer 图层 geom函数
# A tibble: 234 × 11
manufacturer model displ year cyl trans drv cty hwy fl class
<chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
1 audi a4 1.8 1999 4 auto… f 18 29 p comp…
2 audi a4 1.8 1999 4 manu… f 21 29 p comp…
3 audi a4 2 2008 4 manu… f 20 31 p comp…
4 audi a4 2 2008 4 auto… f 21 30 p comp…
5 audi a4 2.8 1999 6 auto… f 16 26 p comp…
6 audi a4 2.8 1999 6 manu… f 18 26 p comp…
7 audi a4 3.1 2008 6 auto… f 18 27 p comp…
8 audi a4 quattro 1.8 1999 4 manu… 4 18 26 p comp…
9 audi a4 quattro 1.8 1999 4 auto… 4 16 25 p comp…
10 audi a4 quattro 2 2008 4 manu… 4 20 28 p comp…
# ℹ 224 more rows
#ggplot()第一项参数data = 指定数据集
#ggplot()第二项参数mapping = aes() aesthetic
#aes()函数x = , y = 指定画布的坐标系
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point()
1.2 美学 Aesthetic: 颜色 形状 大小
若要在图形反映第3个变量的信息,可以在aes()函数中用第3个变量映射color, shape或size。
注意:颜色color、形状shape用定性变量映射,大小size用定量变量映射
思考:如果颜色用定量变量映射,效果如何?
1.3 切面 Facet
在图形中引入定性变量,将样本分隔成几个子集/切面。
#facet_wrap(~drv)按drv的三种取值,分为3个子集
ggplot(mpg, aes(displ, hwy,color = class)) +
geom_point() +
facet_wrap(~drv)+
labs(title = "Scatter Diagram of Displ & HWY")
#facet_grid 按两个定性变量切面
ggplot(mpg, aes(displ, hwy,color = class)) +
geom_point() +
facet_grid(year ~ drv)
2 管道符 pipe operator
快捷键:Ctrl+Shift+M
优点:避免函数的嵌套
#mpg 将作为ggplot()的第一项参数
mpg %>% ggplot(aes(displ, hwy,color = class)) +
geom_point() +
facet_wrap(~drv)
# 使用管道符将 mpg 数据集中的 2008 年的数据筛选出来,并使用 ggplot 函数创建散点图,
# 其中 "displ" 作为 x 轴,"hwy" 作为 y 轴,"class" 作为颜色变量,"drv" 作为分面变量
mpg %>%
filter(year==2008) %>% # 筛选数据
ggplot(aes(displ, hwy,color = class)) + # 定义图形映射
geom_point() + # 添加散点
facet_wrap(~drv) # 分面展示
# 使用管道符将 mpg 数据集中的 "compact" 和 "suv" 类别的数据筛选出来,并使用 ggplot 函数创建散点图,
# 其中 "displ" 作为 x 轴,"hwy" 作为 y 轴,"class" 作为颜色变量,"drv" 作为分面变量
mpg %>%
filter(class == "compact" | class == "suv") %>% # 筛选数据
ggplot(aes(displ, hwy,color = class)) + # 定义图形映射
geom_point() + # 添加散点
facet_wrap(~drv) # 分面展示
3 条形图
3.1 简单条形图
# 使用管道符将 mpg 数据集作为 ggplot() 函数的输入,并将 "manufacturer" 列作为 x 轴
# 使用 geom_bar() 函数创建一个条形图
# col 参数设置条边颜色为5,fill 参数设置填充颜色为5
mpg %>%
ggplot(aes(manufacturer)) +
geom_bar(col = 5, fill = 5)
3.2 帕累托图
# 使用 ggplot() 函数将 mpg 数据集作为输入,并将 "manufacturer" 列作为 x 轴变量,使用 fct_infreq() 函数将频数按降序排列
# 使用 geom_bar() 函数创建一个条形图
# col 参数设置条边颜色为6,fill 参数设置填充颜色为6
# 使用 guides() 函数设置 x 轴标签的角度
# guide_axis() 函数的 angle 参数设置标签的旋转角度
mpg %>% ggplot(aes(fct_infreq(manufacturer))) +
geom_bar(col = 6, fill = 6)+
guides(x = guide_axis(angle = 90))+
labs(title = "Pareto Diagram", x = "Manufacturer")
#geom_text标注频数
mpg %>% #使用管道操作符将mpg数据集传递到ggplot中
ggplot(aes(fct_infreq(manufacturer))) + #指定图形的x轴为制造商,同时按照制造商出现频率排序
geom_bar(col = 5, fill = 5)+ # 添加柱状图层,并指定边框颜色和填充颜色
geom_text(stat = "count", # 添加文本标签层,并指定使用计数统计信息作为标签
aes(label = after_stat(count)), # 将标签内容设置为计数统计信息
vjust = -0.5)+ # 将文本标签向下移动0.5个单位的文字高度
guides(x = guide_axis(angle = 45))+
labs(title = "Pareto Diagram", x = "Manufacturer")
3.3 分组条形图
# position = "dodge" side by side bar plot
mpg %>%
filter(manufacturer == "ford" | manufacturer == "toyota") %>% # 筛选出制造商是 "ford" 或 "toyota" 的汽车数据
ggplot(aes(manufacturer, fill = class)) + # 创建一个 ggplot2 对象,以制造商为 x 轴,以车型为颜色填充
geom_bar(position = "dodge", alpha = 0.5) + # 绘制柱状图,position = "dodge" 表示分组柱状图,alpha = 0.5 表示透明度为 0.5
theme_bw() + # 设置绘图主题为黑白主题
theme(panel.grid.major = element_blank(), # 隐藏主网格线
panel.grid.minor = element_blank()) + # 隐藏次网格线
labs(title = "Class and Manufacturer", x = "manufacturer", y = "Number") # 设置图表的标题、x 轴标签和 y 轴标签
3.4 堆栈分组条形图
#position = "fill" 堆栈
mpg %>%
filter(manufacturer == "ford" | manufacturer == "toyota") %>% # 筛选出制造商是 "ford" 或 "toyota" 的汽车数据
ggplot(aes(manufacturer, fill = class)) + # 创建一个 ggplot2 对象,以制造商为 x 轴,以车型为颜色填充
geom_bar(position = "fill", alpha = 0.5) + # 绘制柱状图,position = "fill" 表示堆叠柱状图,alpha = 0.5 表示透明度为 0.5
theme_bw() + # 设置绘图主题为黑白主题
theme(panel.grid.major = element_blank(), # 隐藏主网格线
panel.grid.minor = element_blank()) + # 隐藏次网格线
labs(title = "Class and Manufacturer", x = "manufacturer", y = "Number") # 设置图表的标题、x 轴标签和 y 轴标签
4 直方图
4.1 普通直方图
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
4.2 直方图上标注频数
mpg %>%
ggplot(aes(cty))+
geom_histogram(col = 1, fill = 5, binwidth = 2)+
stat_bin(aes(label = after_stat(count)), binwidth = 2,
geom = "text",vjust = -0.5)+
scale_y_continuous(limits = c(0,50), breaks = seq(0,50,5))+
scale_x_continuous(breaks = seq(9,35,2))
#为直方图设置渐变填充色
mpg %>%
ggplot(aes(cty))+
geom_histogram(aes(fill = ..count..), col = 1, binwidth = 2)+
stat_bin(aes(label = ..count..), binwidth = 2,
geom = "text",vjust = -0.5)+
scale_y_continuous(limits = c(0,50), breaks = seq(0,50,5))+
scale_x_continuous(breaks = seq(9,35,2))+
scale_fill_gradient(low = "cyan3", high = "cyan")
Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(count)` instead.
This warning is displayed once every 8 hours.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
generated.
4.3 频数折线图
#在直方图上添加频数折线图
mpg %>%
ggplot(aes(cty))+
geom_histogram(col = 1, fill = 5, binwidth = 2)+
geom_freqpoly(col = 2,binwidth = 2)
4.4 分组直方图
#facet_wrap 切面,各个组别填充不同颜色
mpg %>%
ggplot(aes(cty, fill = drv))+
geom_histogram()+
facet_wrap(~drv, ncol = 1)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#在mpg中追加新变量drive
#recode对变量重新编码
mpg <- mpg %>%
mutate(drive = recode(drv,"f" ="Front Drive", "r" = "Rear Drive",
"4" = "Four-Wheel Drive"))
mpg %>%
ggplot(aes(cty, fill = drive))+
geom_histogram()+
facet_wrap(~drive, ncol = 1)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
4.5 分组直方图标注频数
mpg %>%
ggplot(aes(cty, fill = drv))+
geom_histogram()+
facet_wrap(~drv, ncol = 1)+
stat_bin(aes(label =ifelse(..count.. == 0, "", ..count..)),
geom = "text",
vjust = -0.5,
size = 3)+
scale_y_continuous(limits = c(0,30))
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#geom_text()标注频数
mpg %>%
ggplot(aes(cty, fill = drv))+
geom_histogram()+
facet_wrap(~drive, ncol = 1)+
geom_text(stat = "count",
aes(label = ..count.., y = ..count..),
vjust = -0.5,
hjust = 0.5,
size = 2)+
scale_y_continuous(limits = c(0, 25))+
theme(legend.position = "bottom")
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
5 箱线图
5.1 普通箱线图
5.2 分组箱线图
#facet_wrap 切面
#ncol=1 图形排成1列
mpg %>%
ggplot(aes(cty,col = drv))+
geom_boxplot()+
facet_wrap(~drv,ncol=1)
#在aes()中设置X轴映射厂家
#guides(x = guide_axis(n.dodge = 3)) X轴分类标签错位
mpg %>%
ggplot(aes(manufacturer,cty,col = manufacturer))+
geom_boxplot()+
guides(x = guide_axis(n.dodge = 3))
#substr提取trans字符串的第1至4个字符,在mpg中追加变量transmission
mpg$transmission <- substr(mpg$trans,1,4)
mpg %>%
ggplot(aes(cty,col = transmission))+
geom_boxplot()+
facet_wrap(~transmission)+
coord_flip()
#在切面facet_wrap()和在aes()中设置定性变量的输出图形对比
#对比aes()中横轴和纵轴互换位置的输出图形对比
mpg %>%
ggplot(aes(transmission,cty,col = transmission))+
geom_boxplot()
6 散点图
6.2 分组散点图
#aes(cty,hwy,col = drv) drv映射颜色
mpg %>%
ggplot(aes(cty,hwy,col = drv))+
geom_point()+
facet_wrap(~transmission)
6.3 三维定量变量
6.4 四维定量变量
#aes(cty,hwy,col =displ,size=cyl) displ映射颜色 cyl映射散点大小
mpg %>%
ggplot(aes(cty,hwy,col = displ,size=cyl))+
geom_point()+
labs(title = "Fuel Economy in City & Highway",
x = "city miles per gallon",
y = "highway miles per gallon")
mpg %>%
ggplot(aes(cty,hwy,col = transmission,
alpha=0.5))+
geom_point()+
geom_smooth(method = lm, se = F)+
facet_wrap(~transmission)+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())+
labs(title = "Fuel Economy in City & Highway",
x = "city miles per gallon",
y = "highway miles per gallon")
`geom_smooth()` using formula = 'y ~ x'
mpg %>%
ggplot(aes(cty,hwy,col = transmission,alpha=0.3))+
geom_point(aes(size = cyl))+
geom_smooth(method = lm, se = F)+
facet_wrap(~transmission)+
theme_bw()+
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())+
labs(title = "Fuel Economy in City & Highway",
x = "city miles per gallon",
y = "highway miles per gallon")+
theme(plot.title = element_text(size = 16),
axis.text = element_text(color = "blue", size = 12),
strip.text = element_text(color = "blue", size = 12))
`geom_smooth()` using formula = 'y ~ x'
7 本章习题
7.1 ggplot2 绘图: mpg
数据:mpg {ggplot2}
提示:mpg数据集在ggplot2这个包中,先加载ggplot2后,再运行?mpg,查看mpg的帮助文档。
注意:
在完成上述图形时,尽可能美化图形、完善坐标轴、图形标题、主题、颜色等的设置。
提交要求:先将图形都编辑到word文档,然后将word文档转换成图片提交。
利用ggplot2完成以下任务:
任选一个定性变量,绘制条形图。
任选两个定性变量,绘制分组条形图。
任选一个定量变量,绘制直方图。
任选一个定量变量,两个定性变量,绘制分组直方图。
任选两个定量变量,绘制散点图,在散点图上添加趋势线。
任选两个定量变量,绘制散点图,让散点的大小、颜色分别体现第3个、第4个变量的信息。
任选两个定量变量,一个定性变量,绘制分组散点图,添加趋势线。
任选一个定量变量,一个定性变量,绘制分组箱线图。
7.2 ggplot2 绘图:cellphone
数据:cellphone.xlsx 或者 cellphone.csv 变量含义: ID 序号;male:1,男,0,女;brand: 手机品牌;price: 手机价格;cost: 每月生活费
注意:
在完成上述图形时,尽可能美化图形、完善坐标轴、图形标题、主题、颜色等的设置。
提交要求:先将图形都编辑到word文档,然后将word文档转换成图片提交。
利用ggplot2完成以下任务:
任选一个定性变量,绘制条形图。
利用两个定性变量,绘制分组条形图。
任选一个定量变量,绘制直方图。
任选一个定量变量,一个定性变量,绘制分组直方图。
利用两个定量变量,绘制散点图,在散点图上添加趋势线。
利用两个定量变量,绘制散点图,让散点颜色代表某个定性变量的信息。
利用两个定量变量,一个定性变量,绘制分组散点图,添加趋势线。
利用一个定量变量,一个定性变量,绘制分组箱线图。