【问题标题】:R pie chart with percentages带有百分比的 R 饼图
【发布时间】:2021-03-27 08:32:52
【问题描述】:

我有这个 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)

我需要根据类别的频率制作一个饼图,上面标有百分比。

【问题讨论】:

    标签: r pie-chart


    【解决方案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)))
    

    【讨论】:

      【解决方案2】:

      您还可以使用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
      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())
      

      这段代码创建了以下情节:

      【讨论】:

      • 谢谢,但我有一个问题,R 不给我情节,代码没问题,R 接受它们,但不给我情节:(
      • 运行我发布的代码后,您是否只在新行中运行了p2?这应该显示情节。
      • 我做了一点改动,我犯了一个错误,所以它不会运行,但现在它的工作。非常感谢!
      【解决方案3】:

      这是一个使用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 日创建

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-22
        • 1970-01-01
        • 2015-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多