作者:李誉辉
四川大学在读研究生
简介
对于多个变量之间的相关关系,常常使用相关关系图来可视化,R自带有pairs()
函数,
可以画相关关系图,但是比较复杂,我们先介绍基于ggplot2
的GGally
包。
等介绍完,再介绍pairs()
函数。
ggmatrix()
可以将多个ggplot2
绘图对象,按照矩阵进行排列。
1.1
矩阵第1列
1library(ggplot2)
2data(tips, package = "reshape")
3
4head(tips)
5
6g1 <- ggplot(tips, aes(x = total_bill, fill = sex)) +
7 geom_density(show.legend = FALSE)
8
9g2 <- ggplot(tips, aes(x = total_bill, fill = sex)) +
10 geom_histogram(position = position_stack(), show.legend = FALSE) +
11 facet_grid(rows = vars(time))# 以time变量行分面
12
13g3 <- ggplot(tips, aes(x = total_bill, y = tip, color = sex)) +
14 geom_point(show.legend = FALSE)
15
1.2
矩阵第2列
1library(ggplot2)
2
3g4 <- ggplot(tips, aes(x = time, y = total_bill, fill = sex)) +
4 geom_boxplot(show.legend = FALSE)
5
6g5 <- ggplot(tips, aes(x = time, fill = sex)) +
7 geom_bar(position = position_stack(), show.legend = FALSE)
8
9g6 <- ggplot(tips, aes(x = tip, fill = sex)) +
10 geom_histogram(position = position_stack(), show.legend = FALSE) +
11 coord_flip() +
12 facet_grid(cols = vars(time))
13
1.3
矩阵第3列
1library(ggplot2)
2library(dplyr)
3library(tibble)
4
5# 第一个图
6text_1 <- round(cor(tips$total_bill, tips$tip), 3)
7tips_female <- as.tibble(tips) %>% filter(sex == "Female") %>% as.data.frame()
8tips_male <- as.tibble(tips) %>% filter(sex == "Male") %>% as.data.frame()
9text_2 <- round(cor(tips_female$total_bill, tips_female$tip), 3)
10text_3 <- round(cor(tips_male$total_bill, tips_male$tip), 3)
11mytext <- c(text_1, text_2, text_3)
12mytext <- paste0(c("Cor", "Female", "Male"), ":", mytext)
13mytext <- data.frame(text = mytext,
14 x = 5,
15 y = c(6, 4, 2),
16 stringsAsFactors = FALSE)
17
18g7 <- ggplot(data = mytext[-1, ], aes(x = x, y =