How to plot a mosaicplot for a 1x1 contingency table?

人走茶凉 提交于 2020-06-16 03:35:21

问题


Plotting a 1-by-1 contingency table returns an error:

dat <- read.table(textConnection('
foo bar
TRUE TRUE
TRUE TRUE
'), header = TRUE, colClasses=c('logical', 'logical'))
mosaicplot(table(dat))

Error in rep.int(0, ydim) : invalid 'times' value

As I learned, the code in the mosaicplot function doesn't allow to plot a 1-by-1-table. But then, how do I plot a mosaicplot of that table?


Background.

I am plotting a series of dynamically created tables, some of which sometimes happen to have only one column and one row, at other times they have more dimensions. Having an undivided rectangle in that series of mosaicplots is valuable information and easily grasped in that visual representation.


回答1:


One possibility is to coerce the variables to be plotted to factor and specify the possible outcomes in levels (in the desired order). Then zero count cells will be represented as thin lines.

dat[] = lapply(dat, factor, levels = c(TRUE, FALSE))
mosaicplot(table(dat))




回答2:


If you don't want the thin lines of @Henrik's (great!) solution you could substitute one-dimensional cases with a custom plot function.

mpOneDim <- function(tbl, title="table(dat)") {
  dn <- attr(tbl, "dimnames")
  labs <- names(dn)
  levels <- unlist(dn)
  plot.new()
  rect(0.0125, -.035, .985, .99, col="gray", border=1)
  mtext(title, line=1.55, font=2, cex=1.2)
  mtext(labs[1], 1, 1)
  mtext(labs[2], 2, 1)
  mtext(levels[2], 2, -1.15, cex=.7)
  mtext(levels[2], 3, -.75, cex=.7)
}
mpOneDim(table(dat))

In your function do something like this:

if (sum(dim(table(dat))) <= 2) {
  mpOneDim(table(dat))
} else {
  mosaicplot(table(dat))
}

Data:

dat <- structure(list(foo = c(TRUE, TRUE), bar = c(TRUE, TRUE)), class = "data.frame", row.names = c(NA, 
-2L))


来源:https://stackoverflow.com/questions/62243596/how-to-plot-a-mosaicplot-for-a-1x1-contingency-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!