gpt4 book ai didi

r - 绘制 r 两个分类变量

转载 作者:行者123 更新时间:2023-12-02 09:18:29 28 4
gpt4 key购买 nike

我正在使用下面的命令在 R 中绘制两个分类变量

性别有 2 个级别,收入有 9 个级别。

spineplot(main$Gender,main$Income, xlab="Gender", ylab="Income levels: 1 is lowest",xaxlabels=c("Male","Female"))

它生成如下图表 enter image description here

  1. 如何用彩色绘制这张图表?
  2. 如何在每个方框内显示每个收入水平的百分比?例如女性收入水平 1 有 21% 的数据。如何在深色区域内显示 21%
################更新 1

添加可重现的例子

fail <- factor(c(2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1,
1, 1, 1, 2, 1, 1, 1, 1, 1,2,2,2,2),
levels = c(1, 2), labels = c("male", "female"))
gender <- factor(rep(c(1:9),3))
spineplot(fail,gender)

最佳答案

我认为使用 barplot 可能更容易做到这一点,因为 spineplot 不会返回任何有用的信息。

默认值如下,但您可以将条形宽度调整为其他变量(您可以看到返回了 x 轴坐标):

par(mfrow = 1:2)
(barplot(table(gender, fail)))
# [1] 0.7 1.9
(barplot(table(gender, fail), width = table(fail)))
# [1] 10.7 26.9

enter image description here

经过一些最后的润色,我们得到了

tbl <- table(gender, fail)
prp <- prop.table(tbl, 2L)
yat <- prp / 2 + apply(rbind(0, prp[-nrow(prp), ]), 2L, cumsum)

bp <- barplot(prp, width = table(fail), axes = FALSE, col = rainbow(nrow(prp)))

axis(2L, at = yat[, 1L], labels = levels(gender), lwd = 0)
axis(4L)

text(rep(bp, each = nrow(prp)), yat, sprintf('%0.f%%', prp * 100), col = 0)

enter image description here

比较

spineplot(fail, gender, col = rainbow(nlevels(gender)))

enter image description here

关于r - 绘制 r 两个分类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44749598/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com