Issue
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)))
Solution
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)
Or, with the built-in iris
data set:
my_pie(iris, Species)
Created on 2022-08-03 by the reprex package (v2.0.1)
Answered By - Allan Cameron Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.