PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 28, 2022

[FIXED] How can i create a user-defined function to group and plot a pie chart in R?

 November 28, 2022     pie-chart, r, user-defined-functions     No comments   

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)

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)



Answered By - Allan Cameron
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing