简体   繁体   English

带有百分比的 R 饼图

[英]R pie chart with percentages

I have this df我有这个 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)

and I need to make a pie chart from the frequencies of the categories labelled with their percentages.我需要根据标有百分比的类别的频率制作饼图。

You can try你可以试试

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

在此处输入图片说明

You could also make the pie plot using dplyr and ggplot .您还可以使用dplyrggplot制作饼图。 It requires a little more of coding, but the result might be more satisfactory.它需要更多的编码,但结果可能更令人满意。

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
p2 <- ggplot(df_plot, aes(x = "", y = percent, fill = factor(kategorija)))+
  geom_bar(width = 1, stat = "identity") +
  #Transform the bar plot to pie plot
  coord_polar("y", start = 0) +
  #Add labels to each part of the pie and add some theme adjustments
  geom_text(aes(y = cumsum(rev(percent)) - rev(percent)/2, 
                       label = paste(rev(percent),"%")), size=4) +
  # Add label for legend
  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())

This code created the following plot:此代码创建了以下图: 饼图

Here is an easy way to do this using ggstatsplot :这是使用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)

Created on 2021-02-22 by the reprex package (v1.0.0)reprex 包(v1.0.0) 于2021年 2 月 22 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM