Open In App

Pie chart using ggplot2 with specific order and percentage annotations

Last Updated : 09 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The ggplot2 package is a powerful and widely used package for graphic visualization. It can be used to provide a lot of aesthetic mappings to the plotted graphs. This package is widely available in R. The package can be downloaded and installed into the working space using the following command :

install.packages("ggplot2")

A data frame is created initially using the data.frame method which is used to indicate two columns here, namely subject and marks. The data frame values are then grouped by using the subject column values. After these rows are stacked together, the data is summarised by computing the sum of marks belonging to a particular subject. 

The data manipulation then takes place using the mutate component which is used to take as input a new column, computed by the marks divided by their respective sum. It is used to add, modify or delete columns from the already specified data frame. 

Syntax : mutate(new-col-name = fun())

The fun() specifies the function or operation on the basis of which the new column values are created. 

This is further followed by the visualization of the data using the ggplot method. The ggplot method can be used to create a ggplot object. The graphical object is used to create plots by providing the data and its respective points. The data can be plotted using both points as well as lines.

Syntax : ggplot(data, aes = )

Arguments :

data – The data to be plotted
aes – The aesthetic mappings

The mean marks values are used as the y axes plotting. The colours are assigned based on the subject and their respective ut_marks. 

The heights of the bars reflect the values when we use the method geom_col() method. The geom_text method is used to enhance the readability of the data by providing textual annotations.

Syntax : geom_text(label =  , position = )

Arguments :

position – The position adjustment to be given to the overlapping data. 

R




# Importing the required libraries
library(ggplot2)
library(dplyr)
  
# creating a data frame
data_frame <- data.frame(subject=c('maths','maths','sst',
                                   'science','sst','hindi','maths',
                                    'sst','science','hindi','sst'),
                 marks=c(4,5,8,2,15,6,3,7,7,6,3))
  
# creating a pie chart in order 
data_frame %>%
  group_by(subject) %>%
  summarise(ut_marks= sum(marks)) %>%
  mutate(mean_ut=ut_marks/sum(ut_marks)) %>%
  ggplot(aes(x="", y= mean_ut, 
             fill=reorder(subject, ut_marks))) +
            geom_col() + geom_text(aes(label = scales::percent(round(mean_ut,2))), 
            position = position_stack(vjust = 0.5))+
  coord_polar(theta = "y")


Output : 

Pie chart

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads