R语言 马赛克图
Posted 数据驱动实践
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R语言 马赛克图相关的知识,希望对你有一定的参考价值。
Library(vcd)
mosaic(Titanic,shade=T,legend=T)
mosaic(~Class+Sex+Age+Survived,data=Titanic,shade=T,legend=T) #等价于mosaic(Titanic,shade=T,legend=T)
01
—
mosaicplot {graphics}
mosaicplot是R语言graphics图形系统中自带的马赛克图绘图函数,用法如下:
## (默认方法:直接以数据集输入)Default S3 method:
mosaicplot(x, main = deparse1(substitute(x)),
sub = NULL, xlab = NULL, ylab = NULL,
sort = NULL, off = NULL, dir = NULL,
color = NULL, shade = FALSE, margin = NULL,
cex.axis = 0.66, las = par("las"), border = NULL,
type = c("pearson", "deviance", "FT"), ...)
## (函数形式)S3 method for class 'formula'
mosaicplot(formula, data = NULL, ...,
main = deparse1(substitute(data)), subset,
na.action = stats::na.omit)
require(stats)
# 图1
mosaicplot(Titanic, main = "Survival on the Titanic - 图1", color = TRUE)
## Formula interface for tabulated data:
# 图2
mosaicplot(~ Sex + Age + Survived, data = Titanic, main = "Survival on the Titanic - 图2",color = TRUE)
注意:mosaicplot和mosaic绘制马赛克图是基于多(二维以上)列联表。
02
—
mosaic {vcd}
## Default S3 method:
mosaic(x, condvars = NULL,
split_vertical = NULL, direction = NULL, spacing = NULL,
spacing_args = list(), gp = NULL, expected = NULL, shade = NULL,
highlighting = NULL, highlighting_fill = rev(gray.colors(tail(dim(x), 1))),
highlighting_direction = NULL,
zero_size = 0.5, zero_split = FALSE, zero_shade = NULL,
zero_gp = gpar(col = 0), panel = NULL, main = NULL, sub = NULL, ...)
## S3 method for class 'formula'
mosaic(formula, data, highlighting = NULL,
..., main = NULL, sub = NULL, subset = NULL, na.action = NULL)
第1步:了解一下列联表分析
列联分析参考:
2)
# > head(mtcars, 2)
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21 6 160 110 3.9 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21 6 160 110 3.9 2.875 17.02 0 1 4 4
df <- xtabs(~ cyl + gear + vs, data = mtcars)
# > df
# , , vs = 0
#
# gear
# cyl 3 4 5
# 4 0 0 1
# 6 0 2 1
# 8 12 0 2
#
# , , vs = 1
#
# gear
# cyl 3 4 5
# 4 1 8 1
# 6 2 2 0
# 8 0 0 0
第2步:mosaic绘制马赛克图
## 图3
mosaic(df, main = "图3") # 图3
## 图4 公式模式:
## df <- xtabs(~ cyl + gear + vs, data = mtcars)
mosaic(~ cyl + gear + vs, data = mtcars,
main = "图4", shade = TRUE, legend = TRUE)
## 图5
data("PreSex")
mosaic(PreSex, condvars = c(1,4))
mosaic(~ ExtramaritalSex + PremaritalSex | MaritalStatus + Gender,
data = PreSex, main = "图5")
以上是关于R语言 马赛克图的主要内容,如果未能解决你的问题,请参考以下文章
R语言可视化两个以上的分类(类别)变量之间的关系使用vcd包中的Mosaic函数创建马赛克图( Mosaic plots)用可视化的方式展示分类型数据
R语言使用两个分类变量创建双向表(Two Way Table两个分类变量的频率表)实战: 矩阵的双向表dataframe的双向表条形图和马赛克图来可视化频率表
R语言可视化:散点图散点图和折线图(line charts)3D散点图旋转3D散点图气泡图corrgram包可视化相关性矩阵马赛克图( Mosaic plots)hexbin密度图