R语言 使用ggplot2绘制饼图

R语言 使用ggplot2绘制饼图

饼图或圆环图是一种圆形的统计图形技术,它以数字比例划分圆环,将数据作为整体的一部分来表示。在圆环图中,每个切片的弧长与它所代表的数量成正比。饼图在商业世界和大众媒体中被广泛用于了解趋势。

方法

  • 导入模块
  • 创建数据
  • 按照选定的列的值排列数据框的行。
  • Mutate to 从一个数据集创建一个新的变量。
  • 绘制饼状图
  • 显示图表

例1 :

library(ggplot2)
library(dplyr)
  
count.data <- data.frame(
    pilot_class = c("A++(Senior pilot)", "A+(Junior pilot)", "A-(Trainee pilot)", "Crew"),
    n = c(389, 256, 589, 466),
    proportion = c(22.88, 15.0588, 34.647, 27.411)
)
  
count.data
  
count.data <- count.data %>%
    arrange(desc(pilot_class)) %>%
    mutate(lab.ypos = cumsum(proportion) - 0.6*proportion)
  
count.data
  
mycols <- c("#42f55a", "#42f5e6", "#ecf542", "#f56f42")
  
ggplot(count.data, aes(x = "", y = proportion, fill = pilot_class)) +
    geom_bar(width = 1, stat = "identity", color = "black") +
    coord_polar("y", start = 0)+
    geom_text(aes(y = lab.ypos, label = proportion), color = "black")+
    scale_fill_manual(values = mycols) +
    theme_void()

输出

使用ggplot2在R中绘制饼图

例2 :

Name_of_student <- c("Ankit", "Jack", "Prakhar", "Madahav", "shef", 
            "sama", "karthik", "Ritwik", "Agnim", "Harsh")
  
contribution_in_project <- c(.103, .097, .103, .103,.097, .097, .10,.10,.10,.10 )
  
top_ten_contributors <- data.frame(Name_of_student,contribution_in_project)
top_ten_contributors
  
pie_2 <- ggplot(top_ten_contributors, aes(x = factor(1), fill = factor(contribution_in_project))) +
    geom_bar(width = 1)
  
pie_2 + coord_polar(theta = "y")

输出

使用ggplot2在R中绘制饼图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程