R语言 马赛克图

Posted 数据驱动实践

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R语言 马赛克图相关的知识,希望对你有一定的参考价值。

马赛克图是《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)




注意:mosaicplot和mosaic绘制马赛克图是基于多(二维以上)列联表。


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)# 图1mosaicplot(Titanic, main = "Survival on the Titanic - 图1", color = TRUE)
## Formula interface for tabulated data:# 图2mosaicplot(~ Sex + Age + Survived, data = Titanic, main = "Survival on the Titanic - 图2",color = TRUE)

R语言 马赛克图

R语言 马赛克图



注意: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步:了解一下列联表分析


列联分析参考:

head(mtcars, 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绘制马赛克图

## 图3mosaic(df, main = "图3") # 图3

## 图4 公式模式:## df <- xtabs(~ cyl + gear + vs, data = mtcars) mosaic(~ cyl + gear + vs, data = mtcars, main = "图4", shade = TRUE, legend = TRUE)

## 图5data("PreSex")mosaic(PreSex, condvars = c(1,4))mosaic(~ ExtramaritalSex + PremaritalSex | MaritalStatus + Gender, data = PreSex, main = "图5")

R语言 马赛克图

R语言 马赛克图




【往期回顾推荐】