简单介绍一下ggplot2分类别绘图的三种方式:分组、分面、图形组合;以及长、宽数据如何实现分组绘图
使用ggplot2绘图时,若需要分类别进行绘图,常见的方式有:
library(ggplot2)
library(cowplot)
rm(list = ls()) # 清空工作空间!!!
使用R自带的mtcars汽车数据集
print(head(mtcars))
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
str(mtcars)
# 'data.frame': 32 obs. of 11 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
# $ disp: num 160 160 108 258 360 ...
# $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
# $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
# $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
# $ qsec: num 16.5 17 18.6 19.4 17 ...
# $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
# $ am : num 1 1 1 0 0 0 0 0 0 0 ...
# $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
# $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
使用vs作为类别变量,将其转化为因子
mtcars$vs <- factor(mtcars$vs)
table(mtcars$vs)
#
# 0 1
# 18 14
按照颜色进行分组
ggplot(data = mtcars, aes(x = mpg, y = wt, color = vs)) +
geom_point() +
geom_smooth(method = "lm") +
theme_bw()
ggplot(data = mtcars, aes(x = mpg, y = wt)) +
facet_wrap("~ vs") + # 列分面
geom_point() +
geom_smooth(method = "lm") +
theme_bw()
cowplot包的plot_grid函数进行图形组合时,可对齐图形边框与坐标轴,参考链接
# 选择vs = 0的样本;注意mtcars$vs为因子,可先转化为字符串再跟0、1比较
p1 <- ggplot(data = mtcars[as.character(mtcars$vs) == "0", ],
aes(x = mpg, y = wt)) +
geom_point() +
geom_smooth(method = "lm") +
theme_bw()
# 选择vs = 0的样本
p2 <- ggplot(data = mtcars[as.character(mtcars$vs) == "1", ],
aes(x = mpg, y = wt)) +
geom_point() +
geom_smooth(method = "lm") +
theme_bw()
# 将p1、p2横向组合起来
plot_grid(p1, p2, ncol = 2, align = "vh")
data1 <- data.frame(x = c(1, 2, 3, 1, 2, 3),
y = c(1, 2, 3, 2, 4, 6),
group = factor(c(0, 0, 0, 1, 1, 1)))
print(data1)
# x y group
# 1 1 1 0
# 2 2 2 0
# 3 3 3 0
# 4 1 2 1
# 5 2 4 1
# 6 3 6 1
使用颜色进行分组color = group
(使用其他属性如点、线的形状分组与此类似)
ggplot(data = data1, aes(x = x, y = y, color = group)) +
geom_point() +
geom_line() +
theme_bw()
data2 <- data.frame(x = c(1, 2, 3),
y1 = c(1, 2, 3),
y2 = c(2, 4, 6))
print(data2)
# x y1 y2
# 1 1 1 2
# 2 2 2 4
# 3 3 3 6
使用颜色color
进行分组,注意color
是写入aes
里
可以看到,该图与上述长数据绘出的图一模一样
ggplot(data = data2, aes(x = x)) +
geom_point(aes(y = y1, color = "0")) +
geom_line(aes(y = y1, color = "0")) +
geom_point(aes(y = y2, color = "1")) +
geom_line(aes(y = y2, color = "1")) +
labs(y = "y", color = "group") + # 修改y轴标签和图例名称
theme_bw()