0
0
R-programmingHow-ToBeginner · 3 min read

How to Create Pie Chart in R: Simple Guide with Example

To create a pie chart in R, use the pie() function with a numeric vector representing the sizes of slices. You can add labels and customize colors by passing additional arguments like labels and col.
📐

Syntax

The basic syntax of the pie() function is:

  • pie(x, labels = NULL, col = NULL, main = NULL)

Where:

  • x is a numeric vector with values for each slice.
  • labels is an optional character vector for slice names.
  • col is an optional vector of colors for slices.
  • main is an optional title for the chart.
r
pie(x, labels = NULL, col = NULL, main = NULL)
💻

Example

This example creates a pie chart showing the distribution of fruits with labels and colors.

r
fruit_counts <- c(10, 15, 30, 45)
fruit_labels <- c("Apples", "Bananas", "Cherries", "Dates")
colors <- c("red", "yellow", "pink", "brown")
pie(fruit_counts, labels = fruit_labels, col = colors, main = "Fruit Distribution")
Output
A pie chart window opens showing four slices labeled Apples, Bananas, Cherries, and Dates with respective colors red, yellow, pink, and brown.
⚠️

Common Pitfalls

Common mistakes when creating pie charts in R include:

  • Passing non-numeric data to pie(), which causes errors.
  • Not providing labels, resulting in unlabeled slices that are hard to understand.
  • Using too many slices, which makes the chart cluttered and unreadable.
  • Not setting colors, which can make slices look similar and confusing.
r
## Wrong: Non-numeric data
# pie(c("a", "b", "c"))  # This will cause an error

## Right: Numeric data with labels
pie(c(5, 10, 15), labels = c("A", "B", "C"), col = c("blue", "green", "orange"))
Output
A pie chart with three slices labeled A, B, and C in blue, green, and orange colors.
📊

Quick Reference

ArgumentDescription
xNumeric vector of slice sizes
labelsCharacter vector of slice labels (optional)
colVector of colors for slices (optional)
mainTitle of the pie chart (optional)

Key Takeaways

Use the pie() function with a numeric vector to create pie charts in R.
Always provide labels to make the chart easy to understand.
Customize colors to differentiate slices clearly.
Avoid too many slices to keep the chart readable.
Non-numeric data will cause errors in pie charts.