Marginal Histogram / Boxplot
适用于展示两个变量间相关性,同时展现了相关性中每一个点上两个变量的具体情况
# load package and data
library(ggplot2)
library(ggExtra)
data(mpg, package="ggplot2")
# mpg <- read.csv("<http://goo.gl/uEeRGu>")
# Scatterplot
theme_set(theme_bw()) # pre-set the bw theme.
mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
- *晨曦解读:**对数据集进行筛选,然后让我们来看一下筛选完以后的数据集,这里我们可以很清楚的看到,有两个数字型变脸(cty和hwy)(这个应该属于连续型变量),然后有几个可以当作分组变量,分别是第一列和第二列,然后对数据集的探索到这里就可以
g <- ggplot(mpg, aes(cty, hwy)) +
geom_count() + #防止重叠点的函数
geom_smooth(method="lm", se=F)#拟合曲线
ggMarginal(g, type = "histogram", fill="transparent")
ggMarginal(g, type = "boxplot", fill="transparent")
# ggMarginal(g, type = "density", fill="transparent")
- *晨曦解读:**绘图逻辑
#第一图层(设置变量,同时如果有一些图外元素,也可以在这里一起设置,也就是全局映射)
ggplot(mpg, aes(cty, hwy))
#第二图层(点图)(这里设置的为防止重叠的点图)
geom_count()
#第三图层(添加拟合曲线)
geom_smooth(method="lm", se=F)
#第四图层(这里我们添加另一个可视化来帮助我们更好的展示两个变量)
ggMarginal(g, type = "histogram", fill="transparent")#直线图
ggMarginal(g, type = "boxplot", fill="transparent")#箱线图
ggMarginal(g, type = "density", fill="transparent")#密度图
ggMarginal(g, type = "violin", fill="transparent")#小提琴图
- *晨曦解读:**这里只展示前两个可视化,因为剩下两个比较不好看
#直线图
# load package and data
library(ggplot2)
library(ggExtra)
data(mpg, package="ggplot2")
# mpg <- read.csv("<http://goo.gl/uEeRGu>")
# Scatterplot
theme_set(theme_bw()) # pre-set the bw theme.
mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
mpg_select
g <- ggplot(mpg, aes(cty, hwy)) +
geom_count() +
geom_smooth(method="lm", se=F)
ggMarginal(g, type = "histogram", fill="transparent")
#箱线图
# load package and data
library(ggplot2)
library(ggExtra)
data(mpg, package="ggplot2")
# mpg <- read.csv("<http://goo.gl/uEeRGu>")
# Scatterplot
theme_set(theme_bw()) # pre-set the bw theme.
mpg_select <- mpg[mpg$hwy >= 35 & mpg$cty > 27, ]
mpg_select
g <- ggplot(mpg, aes(cty, hwy)) +
geom_count() +
geom_smooth(method="lm", se=F)
ggMarginal(g, type = "boxplot", fill="transparent")