Tuesday, January 20, 2026

Chapter-2:- Pie Chart R-Programming

Example-1:- 
You want to visualize the proportion of traffic your website receives from five different sources. Create a pie chart that include the percentage value on each slice.

Data (Number of visitors): trafficcounts <- c(1200, 800, 450, 300, 250)
Sources: sources <- c("Organic Search", "Direct", "Referral", "Social Media", "Email")

Calculate the percentage for each source
Labels on the slices should show the calculated percentage (eg. 40%)
Include a main title "Website Traffic Sources"
Use a rainbow colour palette
Add a legend showing the source names in the top right corner

Code:-
trafficcounts <- c(1200, 800, 450, 300, 250)
sources <- c("Organic Search", "Direct", "Referral", "Social Media", "Email")
percent <- round(100*trafficcounts/sum(trafficcounts), 1) #calculation of percentage
percentlabels <- paste(sources, "(", percent, "%", ")") # Add % sign

# Define a color palette
colorpalette <- rainbow(length(sources))

# Create the pie chart with percentage labels
pie(trafficcounts, labels = percentlabels, main = "Website Traffic Sources",
    col = colorpalette)

# Add a legend to the top right
legend("topleft", sources,
       cex = 0.5, # Adjust legend size
       fill = colorpalette, inset=c(0,0))


Solution:-


Explanation:-
  • In the 1st and 2nd line we simply take the data which given in example
  • We have to use c to compile the data
  • In 3rd line, first we have to calculate the percentage of each sources, and you here use "round" to round off the data and in last you see 1 means round off to 1 digit
  • In 5th line, we use here to label each pie , here paste0 to combine all the data with 0 gap, if we only write here "paste" then you see gap in the label - Direct(26.7%), Organic Search(40%)
  • In 5th line you see paste0(sources, "(", percent, "%" , ")") --> means it combine all the data first it take data from sources (which we already mention like organic search, direct etc.), after this you see bracket open and then you see percent (means you calculate in 3rd line) ,after that it add % sign and bracket close sign
  • In the 11th line here we use all the parameter like labels to label the pie chart, col use for colours
  • In the 15th line legend use for label the pie in a seperate box , cex use to for adjust the font in the box, inset to place the box in particular position, fill use to show the color in box

All parameter of pie

Parameter

Purpose

x

A vector of non-negative numeric values that determine the areas of the pie slice

labels

A character vector providing names for each slice. If omitted, it defaults to the names of the input vector x

edges

An integer specifying the number of edges used to approximate the circle (default is 200). Lowering this value creates a polygonal shape

radius

A numeric value( typically between -1 and 1) that determines the size of the pie chart. The default is 0.8

clockwise

A logical value; If TRUE, slices are drawn clockwise; If FALSE (default) they are drawn counter-clockwise

init.angle

The starting angle for the first slice in degrees. Defaults to 0 (3 o’clock) for counter clockwise and 90 (12 o’clock) if clockwise= TRUE

col

A vector of colors to fill the slices. If not specified, R uses a default palette of pastel colors

main 

A string of overall title of the plot

density

The density of shading lines (lines per inch). The default NULL means no shading

angle

The slope of shading lines in degrees

border

Specifies the color of the slice borders

lty

The line type used for the slice borders (eg solid, dashed)

cex

Text size





Example-2:-

data <- c (600,300,150,100,200)
labels <-c ("Housing", "Food", "Clothes", "Entertainment", "Other")
--> Draw a 3d pie chart with label the each slice with percentage


Code:-
# Define data and labels
data <- c (600, 300, 150, 100, 200)
labels <- c("Housing", "Food", "Clothes", "Entertainment", "Other")

#Calculate percentages
percentage <- round(100 * data / sum(data), 1)

#label the pie slice
labelbox <- paste(labels, "-", percentage, "%", sep='')
# You can either use paste0 or paste with sep=' ' to reduce the gap

# Create the 3D Pie Chart
pie3D(data, 
      labels = labelbox, 
      explode = 0.1,                # Separates slices slightly
      main = "Monthly Expenditure",    # Title of the chart
      col = rainbow(length(data)),        # Vibrant color palette
      labelcex = 0.8)              # Adjust label text size


Solution:-


Explanation:-
  • In 2nd and 3rd line you see the data as given in example
  • In 6th line we first calculate the percentage of each pie slice
  • In 9th line we label the complete name which we want to mention in each slice of pie, we use here paste so we combine the name with percentage and here use sep=" if we reduce the gap between the data or which we can use either "paste0"
  • In 13th line we use all the parameter of pie3d (for run pie3d download plotrix from library)
  • "explode" use to seperate slice slightly
  • "labelcex" use to resize the font size

All parameter of pie3D

Parameter

Purpose

x

A numeric vector where each value represents a sector of the pie

labels

An optional character vector providing names for each sector

radius

A numeric value specifying the radius of the pie in user units (default is 1)

height

The thickness or depth of the pie (default is 0.1)

theta

The viewing angle of the pie in radians (default is 𝜋/6).Changing this affects the 3D tilt

start

The starting angle at which to begin drawing the sectors, in radians (default is 0).

explode

A numeric value or vector indicating how much to “explode” or separate the slices from the center (default is 0)

col

A vector of colors used to fill the slices

border

The color of the sector border lines (default is par (“fg”))

shade

A value between 0 and 1 that determines the reduction in brightness for the sides of the sectors to enhance the 3D effect (default is 0.8)

edges

The number of lines used to form the ellipse (default is NA)


Label Customization:-

labelpos

Optional numeric vector specifying the positions of the labels

labelcol

The color of the label text

labelcex

The character expansion factor (size) for the label (default is 1.5)


Layout and Ordering:-

sector.order

Allows you to specify the exact order in which sectors are drawn, which can help fix overlapping issues in 3D

mar

A numeric vector specifying the margin around the pie

pty

A character value specifying whether to force a square plot region (“s”, default) or allow non-square regions (“m”)

No comments:

Post a Comment

Chapter-5:- Scatter Plot in R-programming

 Chapter-5:- Scatter Plot in R-programming Example-1:-  Create a scatter plot of car weight on x-axis and miles per gallon on y-axis by pre-...