GGally与pairs相关关系图_史上最全(一)

640?wx_fmt=png

作者:李誉辉  

四川大学在读研究生


简介
对于多个变量之间的相关关系,常常使用相关关系图来可视化,R自带有pairs()函数,
可以画相关关系图,但是比较复杂,我们先介绍基于ggplot2GGally包。
等介绍完,再介绍pairs()函数。


1.ggmatrix()

ggmatrix()可以将多个ggplot2绘图对象,按照矩阵进行排列。


1.1

矩阵第1列


 1library(ggplot2)
2data(tips, package = "reshape")
3
4head(tips)
5
6g1 <- ggplot(tipsaes(x = total_bill, fill = sex)) + 
7  geom_density(show.legend = FALSE)
8
9g2 <- ggplot(tipsaes(x = total_bill, fill = sex)) + 
10  geom_histogram(position = position_stack(), show.legend = FALSE) + 
11  facet_grid(rows = vars(time))# 以time变量行分面
12
13g3 <- ggplot(tipsaes(x = total_bill, y = tip, color = sex)) + 
14  geom_point(show.legend = FALSE)
15


640?wx_fmt=png


1.2

矩阵第2列


 1library(ggplot2)
2
3g4 <- ggplot(tipsaes(x = time, y = total_bill, fill = sex)) + 
4  geom_boxplot(show.legend = FALSE)
5
6g5 <- ggplot(tipsaes(x = time, fill = sex)) + 
7  geom_bar(position = position_stack(), show.legend = FALSE)
8
9g6 <- ggplot(tipsaes(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_billtips$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_billtips_female$tip), 3)
10text_3 <- round(cor(tips_male$total_billtips_male$tip), 3)
11mytext <- c(text_1text_2text_3)
12mytext <- paste0(c("Cor", "Female", "Male"), ":", mytext)
13mytext <- data.frame(text = mytext,
14                     x = 5,
15                     y = c(6, 42),
16                     stringsAsFactors = FALSE)
17
18g7 <- ggplot(data = mytext[-1, ], aes(x = x, y = 
  • 15
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值