如何在R语言的mosaicplot中添加表格数值与百分比标签?
如何给马赛克图添加单元格数值和百分比标签?
我来帮你解决这个问题!你遇到的vcd包报错是因为参数使用方式不对,同时也可以用基础绘图的方法手动添加标签,下面给你两种可行的方案:
首先先重现你的数据和初始绘图代码,方便参考:
你的交叉表x
# 创建并格式化交叉表 x <- table(married_working_women$fem_ed, married_working_women$hom_ed) rownames(x) <- c("< HS", "HS", "> HS") colnames(x) <- c("< HS", "HS", "> HS") x
输出结果:
< HS HS > HS < HS 2410 112 283 HS 63 83 55 > HS 44 49 172
你初始的马赛克图代码
library(RColorBrewer) mosaicplot(x, main = "Education Levels of Working Spouses", xlab = "Wife's Education", ylab = "Husband's Education", las = 1, color = brewer.pal(3, name = "Pastel2"))
方案1:用基础绘图的mosaicplot手动添加标签
mosaicplot支持返回每个单元格的坐标信息,我们可以利用这个来精准添加数值和百分比标签:
library(RColorBrewer) # 绘制马赛克图并保存单元格坐标(关键:return=TRUE) mp <- mosaicplot(x, main = "Education Levels of Working Spouses", xlab = "Wife's Education", ylab = "Husband's Education", las = 1, color = brewer.pal(3, name = "Pastel2"), return = TRUE) # 计算总百分比,准备标签(数值+百分比) total <- sum(x) pct <- round(100 * x / total, 1) labels <- paste(x, "\n(", pct, "%)", sep = "") # 计算每个单元格的中心坐标 x_centers <- rowMeans(mp$x)[rep(1:nrow(x), ncol(x))] y_centers <- colMeans(mp$y)[rep(1:ncol(x), each = nrow(x))] # 将标签添加到单元格中心 text(x_centers, y_centers, labels = labels, cex = 0.8)
如果你需要行百分比或列百分比,只需要修改pct的计算方式:
- 行百分比:
pct <- round(100 * x / rowSums(x), 1) - 列百分比:
pct <- round(100 * x / colSums(x), 1)
方案2:正确使用vcd包的mosaic函数解决报错
你之前的报错是因为labeling_cells的参数传递有误,正确的做法是直接传递和表格维度匹配的标签矩阵,以下是修正后的代码:
library(vcd) library(RColorBrewer) # 准备标签:这里用「数值+总百分比」的格式 total <- sum(x) labels <- paste(x, "\n(", round(100*x/total, 1), "%)", sep = "") # 正确调用mosaic函数 mosaic(x, main = "Education Levels of Working Spouses", xlab = "Wife's Education", ylab = "Husband's Education", las = 1, # 设置填充色,替代base里的color参数 gp = gpar(fill = brewer.pal(3, "Pastel2")), # 添加单元格标签 labeling = labeling_cells( text = labels, gp_text = gpar(cex = 0.8) # 调整文字大小 ), legend = FALSE) # 不需要图例可以设为FALSE,按需调整
报错原因说明:
之前你用round(x, 2)作为text参数,虽然x是表格,但labeling_cells需要的是和表格维度一致的矩阵(字符或数值型),直接传递处理好的labels矩阵或原始的as.matrix(x)即可,不需要额外的索引操作,这就是导致你出现「subscript out of bounds」错误的原因。
如果只想显示原始数值,把text参数改成text = as.matrix(x)就行;如果只想显示百分比,改成text = round(100*x/sum(x),1)即可。
内容的提问来源于stack exchange,提问作者Saïd Maanan
相关产品推荐
相关产品推荐

