gpt4 book ai didi

r - 如何从具有相对频率的表中绘制 R 中的饼图?

转载 作者:行者123 更新时间:2023-12-02 07:22:37 24 4
gpt4 key购买 nike

我是 R 的新手。我需要绘制饼图。现在我已经尽力了,但它没有为我生成饼图。下面是我的代码。

socialIssue <- matrix(c(245,112,153,71,133,306),ncol=1,byrow=T)
rownames(socialIssue) <- c("Housing","Transportation","Health Care","Education","Food","Other")
colnames(socialIssue) <- c("Frequency")
socialIssue <- as.table(socialIssue)
socialIssue/sum(socialIssue)

cols <- rainbow(nrow(socialIssue))
pie(socialIssue$Frequency, labels=paste0(round(socialIssue$Frequency/sum(socialIssue$Frequency)*100,2),"%"),colnames=cols)

这是以下输出。输出的频率是正确的。

socialIssue <- matrix(c(245,112,153,71,133,306),ncol=1,byrow=T)
> rownames(socialIssue) <- c("Housing","Transportation","Health Care","Education","Food","Other")
> colnames(socialIssue) <- c("Frequency")
> socialIssue <- as.table(socialIssue)
> socialIssue/sum(socialIssue)
Frequency
Housing 0.24019608
Transportation 0.10980392
Health Care 0.15000000
Education 0.06960784
Food 0.13039216
Other 0.30000000
>
> cols <- rainbow(nrow(socialIssue))
> pie(socialIssue$Frequency, labels=paste0(round(socialIssue$Frequency/sum(socialIssue$Frequency)*100,2),"%"),colnames=cols)
Error in socialIssue$Frequency : $ operator is invalid for atomic vectors

最佳答案

转换为dataframe然后绘图

socialIssue = as.data.frame(socialIssue)
socialIssue$percent = round(100*socialIssue$Freq/sum(socialIssue$Freq), digits = 1)
socialIssue$label = paste(socialIssue$Var1," (", socialIssue$percent,"%)", sep = "")
pie(socialIssue$Freq, labels = socialIssue$label, col = cols)

enter image description here

关于r - 如何从具有相对频率的表中绘制 R 中的饼图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41688201/

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