R Pie Charts

Pie Charts

A pie chart is a circular graphical view of data.Use the pie() function to draw pie charts:

Example
# Create a vector of pies
x <- c(10,20,30,40)

# Display the pie chart
pie(x)

Output:

As you can see the pie chart draws one pie for each value in the vector (in this case 10, 20, 30, 40).By default, the plotting of the first pie starts from the x-axis and move counterclockwise.

Note: The size of each pie is determined by comparing the value with all the other values, by using this formula: The value divided by the sum of all values: x/sum(x)

Start Angle

You can change the start angle of the pie chart with the init.angle parameter.The value of init.angle is defined with angle in degrees, where default angle is 0.

Example

Start the first pie at 90 degrees:
# Create a vector of pies
x <- c(10,20,30,40)

# Display the pie chart and start the first pie at 90 degrees
pie(x, init.angle = 90)

Output;

Labels and Header

Use the label parameter to add a label to the pie chart, and use the main parameter to add a header:

Example
# Create a vector of pies
x <- c(10,20,30,40)

# Create a vector of labels
mylabel <- c("2019", "2020", "2021", "2022")

# Display the pie chart with labels
pie(x, label = mylabel, main = "Growth")

Output:

Colors

You can add a color to each pie with the col parameter:
# Create a vector of pies
x <- c(10,20,30,40)

# Create a vector of labels and colors
mylabel <- c("2019", "2020", "2021", "2022")
colors <- c("blue", "yellow", "green", "black")

# Display the pie chart with labels
pie(x, label = mylabel,col=colors, main = "Growth")

output:


Legend

To add a list of explanation for each pie, use the legend() function:
# Create a vector of pies
x <- c(10,20,30,40)

# Create a vector of labels
mylabel <- c("2019", "2020", "2021", "2022")
colors <- c("blue", "yellow", "green", "black")

# Display the pie chart with labels
pie(x, label = mylabel,col=colors, main = "Growth")
legend("bottomright", mylabel, fill = colors)

Output:

The legend can be positioned as either:

bottomright, bottom, bottomleft, left, topleft, top, topright, right, center

Create a 3D Pie Chart in R

In order to create a 3D pie chart, first we need to import the plotrix package. Then, we use the pie3D() function to create a 3D pie chart. For example,
# import plotrix to use pie3D() 
library(plotrix) 
 expenditure <- c(600, 300, 150, 100, 200) 
 result <- pie3D(expenditure, main = "Monthly Expenditure Breakdown", labels = c("Housing", "Food", "Cloths", "Entertainment", "Other"), col = c("red", "orange", "yellow", "blue", "green") ) 

 print(result)

Output:


Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types