Open In App

Pie chart with facet_wrap in R

Improve
Improve
Like Article
Like
Save
Share
Report

In general, Facetting is the process that refers to the split of the output chart(plot) window as grids to display similar charts under the same section. This can be achieved for the plots which are plotted using the ggplot2 package in R Programming Language.

Syntax: facet_wrap(facets, nrow, ncol, scales, shrink, dir, strip.position)

Where,

  • facets –  the set of grouped variables(data table)
  • nrow, ncol – to specify the number of rows and columns respectively
  • scales – the scales should be fixed or free is specified here
  • shrink – If TRUE, will shrink scales to fit output of statistics
  • dir – Used to specify direction of plot (“h” for horizontal or “v”, for vertical.)
  • strip.position – Used to specify the position of labels

Steps to Plot Pie Chart With facet_wrap()

Install and load the required package.

R




install.pckages("data.table")
install.packages("ggplot2")
 
library(ggplot2)
library(data.table)


Creation of sample data frame with groups and sub-groups and converting it to data table as follows.

R




df <- data.frame(
Names = c("Anu","Bhuvana","Dilip","Harika",
          "Harish","Tarun","Srujan","Sandhya"),
Company = c("Microsoft","Adobe","Adobe",
            "Microsoft","Meta","Meta",
            "Microsoft","Adobe"),
Branch =c("CSE","IT","CSE","CSE","IT",
          "IT","CSE","IT")
)
# Conversion of data frame to data table
dt <- data.table(df)
print(dt)


Output:

Sample data frame to make pie chart

Sample data frame to make a pie chart

Basic Pie plot using ggplot2 package for our data frame.

R




pie_plot <- ggplot2::ggplot(dt,aes(x=1, y=Branch, fill=Company)) +
            geom_bar(stat="identity", width=2) +
            coord_polar(theta='y') +
            labs(title="Basic Pie Plot using ggplot")
pie_plot


Output:

Pie Chart using ggplot

Pie Chart using ggplot

In this example, we are facetting pie chart based on branches of students as follows using the facet_wrap() function

R




pie_plot <- pie_plot+facet_wrap(~Branch)
pie_plot


Output:

Pie Chart using facet_wrap()

Pie Chart using facet_wrap()



Last Updated : 06 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads