带百分比的R饼图

时间:2019-12-29 19:49:33

标签: r pie-chart

我有这个df

species<-c("Platanus acerifolia Willd.","Platanus acerifolia Willd.","Platanus occidentalis L.",
           "Morus alba L.","Platanus occidentalis L.","Celtis australis L.")
kategorija<-c(3,2,1,2,3,3)

df<-data.frame(species,kategorija)

我需要从带有百分比标记的类别的频率中制作饼图。

3 个答案:

答案 0 :(得分:1)

您可以尝试

pie(table(df$kategorija), labels = paste(round(prop.table(table(df$kategorija))*100), "%", sep = ""), col=rainbow(nrow(df)))
legend('topright', legend = paste('category', table(df$kategorija)), fill=rainbow(nrow(df)))

enter image description here

答案 1 :(得分:1)

您还可以使用dplyrggplot绘制饼图。它需要更多的编码,但是结果可能会更令人满意。

library(ggplot2)
library(dplyr)

#Use dplyr to get percentages per kategorija
df_plot<-df %>% 
  count(kategorija) %>% 
  mutate(percent = round((100 * n / sum(n)),2))

#Create the bar plot
p1<- ggplot(df_plot, aes(x = "", y = percent, fill = factor(kategorija)))+
  geom_bar(width = 1, stat = "identity")
#Transform the bar plot to pie plot
p2 <- p1 + coord_polar("y", start = 0)
#Add labels to each part of the pie and add some theme adjustments
p2 <- p2 + geom_text(aes(y = cumsum(rev(percent)) - rev(percent)/2, 
                       label = paste(rev(percent),"%")), size=4) +
  labs(fill = "Kategorija")+
  theme_minimal() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text = element_blank(),
        panel.border = element_blank(),
        panel.grid=element_blank(),
        axis.ticks = element_blank())

此代码创建了以下图: Pie plot

答案 2 :(得分:0)

这是使用 ggstatsplot 执行此操作的简单方法:

library(ggstatsplot)

species <- c(
  "Platanus acerifolia Willd.", "Platanus acerifolia Willd.", "Platanus occidentalis L.",
  "Morus alba L.", "Platanus occidentalis L.", "Celtis australis L."
)

kategorija <- c(3, 2, 1, 2, 3, 3)

df <- data.frame(species, kategorija)

ggpiestats(df, species, counts = kategorija, results.subtitle = FALSE)

reprex package (v1.0.0) 于 2021 年 2 月 22 日创建