如何从具有相对频率的 table 在 R 中绘制饼图?

How to plot pie chart in R from a table with relative Frequency?

我是 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)

这样做:

pie(socialIssue[, 1],
    labels = paste0(round(socialIssue[, 1] / sum(socialIssue[, 1]) * 100, 2), "%"))

因为你有一个矩阵,而不是数据框。

prop.table 负责 % 计算 - sprintf 处理数值的格式,因此您的小数位保持一致。

也不需要所有转换代码:

socialIssue <- matrix(c(245,112,153,71,133,306),ncol=1,byrow=T)
pie(socialIssue, labels=sprintf("%.2f%%", prop.table(socialIssue)*100))

使用基础 R,使用您使用的颜色(参数名称应该是 cols 而不是 `colnames'),添加了图例:

pie(socialIssue[,1], labels=paste0(round(socialIssue/sum(socialIssue)*100,2),"%"),col=cols)
legend('bottomright', legend=rownames(socialIssue), fill=cols, bty='n')

ggplot2

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")
library(ggplot2)
library(scales)
ggplot(as.data.frame(socialIssue), aes(x='',y=Frequency, fill=as.factor(Frequency))) + 
  geom_bar(width=1, stat='identity')  +   
  scale_fill_manual(values=cols, labels=rownames(socialIssue)) +
  scale_y_continuous(labels=percent) + 
  coord_polar(theta = "y") + theme_bw()