简体   繁体   中英

Cross tabulation plot with numbers in R

I would like to add the frequency numbers of each combination on a cross-tabulation plot.

For example, with the mtcars example:

data("mtcars")
table(mtcars$vs, mtcars$am)

We have the number of each combination between $vs and $am columns. If I directly plot this, I get 4 rectanges which size vary based on the frequency numbers:

plot(table(mtcars$vs, mtcars$am), main = "Cross tabulation plot",
     xlab = "Engine (vs)", ylab = "Transmission (am)")

在此处输入图像描述

Would it be possible to print these frequency numbers within the corresponding rectangle in an elegant way?

In this way you can show a number in each square. Basically the idea is to calculate the position of the numbers so that they will fit the center of the square.

tbl <- table(mtcars$vs, mtcars$am)
prpX <- prop.table(table(mtcars$vs))
prpY <- prop.table(table(mtcars$vs, mtcars$am), margin = 1)

plot(tbl, main = "Cross tabulation plot",
     xlab = "Engine (vs)", ylab = "Transmission (am)")
text(prpX/2 * c(1,-1) + 0:1,
     prpY/2 * c(-1,-1,1,1) + c(1,1,0,0),
     tbl)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM