我正在尝试使用R为数据集中的每一列显示不同值出现的百分比。
此简单的代码行从指定的列创建一个表,并显示具有正确分布的完美饼图。但是,我似乎无法显示百分比值。
我相信有一个简短的方法可以做到这一点。
这是我到目前为止所拥有的。请问我需要添加什么?
> workclass <- table(adult$workclass)
> pie(workclass)
谢谢。
这些是我的“饼图”中“我的工作类别”列中的值。我只需要在饼图上显示它们的百分比分布即可。
Federal-gov - 1836 Occurrences
Local-gov - 960 Occurrences
Never-worked - 2093 Occurrences
Private - 120 Occurrences
Self-emp-inc - 2541 Occurrences
Self-emp-not-inc - 1116 Occurrences
State-gov - 2093 Occurrences
Without-pay - 1298 Occurrences
答案 0 :(得分:1)
我希望这段代码对您有用,以便在饼图中显示百分比。
adult <- data.frame(workclass = c(rep("Federal-gov",1836),rep("Local-gov",960),rep("Never-worked",2093),
rep("Private",120), rep("Self-emp-inc",2541), rep("Self-emp-not-inc",1116),
rep("State-gov",2093),rep("Without-pay",1298)))
Occurrences = c(1836,960,2093,120,2541,1116,2093,1298))
workclass <- table(adult$workclass)
par(mar = c(2,2,2,2))
lb = paste0(round(prop.table(workclass)*100,2),"%")
pie(workclass,labels = lb, col = rainbow(8))
legend(-2.1,0.4,legend=names(workclass),cex=0.7,yjust=0.2, xjust = -0.1,
fill = rainbow(8), bty = "n")
prop.table(workclass)
Federal-gov Local-gov Never-worked Private Self-emp-inc Self-emp-not-inc
0.152276686 0.079621796 0.173592104 0.009952725 0.210748943 0.092560338
State-gov Without-pay
0.173592104 0.107655304