条形图是最基础、最常见的图形之一,条形图的种类比较多,包括水平、并列、堆积、百分比等各种条形图类型。
今天来学习下条形图的绘制以及给条形图添加标签。
1. 加载数据
使用moonBook包的acs数据集,数据集包含了857例急性冠脉综合征患者的常见临床数据,数据集中的常见变量包括年龄、性别、心源性休克、出院诊断、射血分数、身高、体重、BMI、肥胖、血脂数据、吸烟等。
library(moonBook)
data(acs)
View(acs)
2. 绘制基础图形
Dx表示出院诊断,包括3个水平:STEMI、NSTEMI 和 Unstable Angina。
library(ggplot2)
ggplot(acs, aes(x=Dx)) + # 指定数据集和x轴数据
geom_bar() + # 指定需绘制的几何对象
theme_bw(base_size = 20) # 设置主题的基本字体大小
可以添加coord_flip()参数来绘制水平条形图。
3. 映射分组变量
smoking是指患者是否具有吸烟史,分有和无两种。
3.1 堆积条形图
geom_bar()中默认参数为position = "stack",表示默认绘制堆积条形图。
ggplot(acs, aes(x=Dx, fill = smoking)) + # 映射分组变量
geom_bar() +
theme_bw(base_size = 20)
设置geom_text()来添加条形图的标签,并设置相关参数调整标签美学属性。
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar() +
theme_bw(base_size = 20) +
geom_text(aes(label = ..count..), stat = 'count',
position = position_stack(vjust = 0.5), # 设置标签位置属性
size = 8, color = "white") # 设置标签大小和颜色
3.2 并列条形图
可以设置position = "dodge"绘制并列条形图。
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "dodge") +
theme_bw(base_size = 20)
设置geom_text()来添加条形图的标签,并设置相关参数调整标签美学属性。
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "dodge") +
theme_bw(base_size = 20) +
geom_text(aes(label = ..count..), stat = 'count',
position = position_dodge(0.9), vjust = -0.2,
size = 8, color = "black")
3.3 百分比条形图
可以设置position = "fill"绘制百分比条形图。
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "fill") +
theme_bw(base_size = 20)
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "fill") +
theme_bw(base_size = 20) +
geom_text(aes(label = ..count..), stat = 'count',
position = position_fill(vjust = 0.5),
size = 8, color = "black")
上面的标签显示的计数值,而不是百分比数值,如果要显示百分比数值,可以运行下述代码。
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "fill") +
theme_bw(base_size = 20) +
geom_text(aes(label = scales::percent(..count../sum(..count..))),
stat = 'count',
position = position_fill(vjust = 0.5),
size = 8, color = "black")
但是上面的百分比是总和的百分比,而不是某一水平的百分比数值。
我们要先计算出每一水平每部分的百分比,再添加上去。
这里重新修改了下参考书籍上代码,使用tidyverse数据科学系列的代码。
library(tidyverse)
res <- acs %>% # 指定数据集
group_by(Dx, smoking) %>% # 指定分组变量
summarise(freq = n()) %>% # 计算频数
ungroup() %>% # 解除分组
group_by(Dx) %>% # 重新指定分组变量
mutate(freq_pct = freq/sum(freq)) # 创建新变量,计算频数百分比
res
ggplot(acs, aes(x=Dx, fill = smoking)) +
geom_bar(position = "fill") +
theme_bw(base_size = 20) +
geom_text(data = res, aes(label = scales::percent(freq_pct), y = freq_pct),
position = position_fill(vjust = 0.5),
size = 8, color = "black")
以上资料来自Learn ggplot2 Using Shiny App,代码有所改动。