【问题标题】:Add labels to a mosaic plot in R将标签添加到 R 中的马赛克图
【发布时间】:2023-01-20 01:26:47
【问题描述】:

我有下表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 函数添加标签的提示吗?非常感谢你提前。

【问题讨论】:

    标签: r plot mosaic-plot


    【解决方案1】:

    我不确定为什么,但关键是永远不要使用 colnames(x)rownames(x)。创建表时,您应该使用 dimnames(x) 代替。代码基于此RStudio post 和此Stackoverflow 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)
    

    【讨论】:

    • 谢谢,您的回答非常有效。
    猜你喜欢
    • 2018-06-11
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2021-01-09
    • 1970-01-01
    • 2020-07-07
    相关资源
    最近更新 更多