如何在 R 中一同可视化两个分类变量?
可以借助镶嵌图轻松地可视化分类变量。在镶嵌图中,可以有一个或多个分类变量,并且根据变量中每个类别的频率来创建绘图。若要在基础 R 中创建镶嵌图,可以 mosaicplot 函数。频率较高的类别以较大尺寸的方框显示,而频率较低的类别则以较小尺寸的方框显示。
考虑以下数据框 −
示例
x1<-sample(c("Lower","Middle","Upper"),20,replace=TRUE) x2<-sample(c("Male","Female"),20,replace=TRUE) df<-data.frame(x1,x2) df
输出
x1 x2 1 Lower Female 2 Upper Male 3 Upper Male 4 Lower Male 5 Lower Female 6 Middle Female 7 Middle Female 8 Middle Female 9 Upper Female 10 Middle Female 11 Lower Female 12 Lower Male 13 Middle Male 14 Lower Male 15 Upper Female 16 Upper Female 17 Upper Male 18 Upper Male 19 Middle Male 20 Middle Female
为上述数据创建镶嵌图 −
示例
mosaicplot(x2~x1,data=df)
输出
示例
mosaicplot(x2~x1,data=df,col=c("Blue","Red"))
输出
广告