Home > Blockchain >  How can i create a user-defined function to group and plot a pie chart in R?
How can i create a user-defined function to group and plot a pie chart in R?

Time:08-04

I want to create a function that groups and creates a pie chart all at once.

# Data example
student_id <- c("001","002","003","004","005","006","007","008","009","010")
student_name <- c("liam", "Bolivia", "Emma", "ava", "Mia", "lucas", "james", "noha", "henry", "alen")
student_sex <- c("m","f","f","f","f","m","m","m","m","m")
student_data <- data.frame(student_id,student_name,student_sex)

# Grouping data on the bases of sex
student_sex_type <- student_data %>%
     group_by(student_sex) %>%
     summarise(count = length(student_id))
student_sex_type

# Plotting pie chart
piepercent <- round(100*student_sex_type$count/sum(student_sex_type$count), 1)

legends <- student_sex_type$student_sex

pie(student_sex_type$count, labels = piepercent, main = "tudent sex", col = rainbow(length(student_sex_type$count)))
legend("topright",legends , cex = 0.8, fill = rainbow(length(student_sex_type$count)))

CodePudding user response:

The following function is straightforward and uses only base R functions. Just give it the name of your data frame and the column you wish to display as a pie chart:

my_pie <- function(data, grouping_var, main = deparse(substitute(data))) {
  
  tab <- table(data[[deparse(substitute(grouping_var))]])
  pie(tab, labels = round(100 * tab / sum(tab), 1), main = main,
      col = rainbow(length(tab)))
  legend("topright", names(tab), cex = 0.8, fill = rainbow(length(tab)))
}

So, with your own data we can do:

my_pie(student_data, student_sex)

enter image description here

Or, with the built-in iris data set:

my_pie(iris, Species)

enter image description here

Created on 2022-08-03 by the reprex package (v2.0.1)

  • Related