向R中的镶嵌图添加标注

k4ymrczo  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(195)

我有下面的表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"))

这给出了这个结果:

现在我想把表x中的数字,可能还有百分比,添加到马赛克图中。

我尝试使用mosaic函数,但它给出了一个错误:

> library(vcd)
> mosaic(x, labeling = labeling_cells(text = round(x, 2)), legend = TRUE)
Error in `[.default`(c(2410, 63, 44, 112, 83, 49, 283, 55, 172), `NA` = NA_character_,  : 
  subscript out of bounds

有谁能给予我一个提示,告诉我如何给mosaicplot函数添加标签吗?提前非常感谢。

sqserrrh

sqserrrh1#

我不知道为什么,但关键是永远不要使用colnames(x)rownames(x)。在创建表时应该使用dimnames(x)。代码基于RStudio postStackOverflow post

library(tidyverse)
library(RColorBrewer)
library(vcd)

x <- read_delim("
2410 112 283
63 83 55
44 49 172", col_names = FALSE)
x <- as.table(as.matrix(x))

dimnames(x) <- list(A = c("< HS", "HS", "> HS"),
                    B = c("< HS", "HS", "> HS")) 
percentages <- round(100*prop.table(x), 3)
txt <- as.table(matrix(paste0(x, "; ", percentages, "%"), 3, 3))
dimnames(txt) <- dimnames(x)

vcd::mosaic(x, pop = F, shade = T, colorize = T, 
            gp = gpar(fill = matrix(c("grey", "green", "red", "blue", "yellow", "blue", "red", "green", "grey"),  3, 3)))

labeling_cells(text = txt, margin = 0)(x)

相关问题