How to Create a Pie Chart in R

Here are two ways to create a pie chart in R:

(1) Using the base pie() function in R:

# Sample data
values <- c(15, 25, 40)
labels <- c("X", "Y", "Z")

# Build the pie chart
pie(values, labels = labels, main = "My Pie Chart")

(2) Using the ggplot2 package:

First install the ggplot2 package:

install.packages("ggplot2")

Then apply the following script to create the pie chart in R:

library(ggplot2)

# Sample data
data <- data.frame(
  values = c(15, 25, 40),
  labels = c("X", "Y", "Z")
)

# Build the pie chart
ggplot(data, aes(x = "", y = values, fill = labels)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y") +
  labs(title = "My Pie Chart") +
  theme_minimal() +
  theme(axis.text = element_blank(), 
        axis.title = element_blank(),
        legend.position = "bottom")

Further customization of the pie chart:

library(ggplot2)

# Sample data
data <- data.frame(
  values = c(15, 25, 40),
  labels = c("X", "Y", "Z")
)

# Build the pie chart
pie_chart <- ggplot(data, aes(x = "", y = values, fill = labels)) +
  geom_bar(stat = "identity", width = 1, color = "white") +
  coord_polar("y") +
  labs(title = "My Pie Chart") +
  theme_minimal() +
  theme(axis.text = element_blank(), 
        axis.title = element_blank(),
        legend.position = "bottom")

# Customizing colors (using html colors) and labels
pie_chart +
  scale_fill_manual(values = c("#fc9f9f", "#98ebb6", "#a5d9f0")) + 
  geom_text(aes(label = paste0(labels, ": ", values, "%")), position = position_stack(vjust = 0.5)) +
  theme(legend.title = element_blank(),
        plot.title = element_text(hjust = 0.5, size = 20, face = "bold"),
        plot.subtitle = element_text(hjust = 0.5, size = 12),
        legend.text = element_text(size = 12, face = "italic"),
        axis.line = element_blank(),
        plot.margin = unit(c(1, 1, 1, 1), "cm"))

Leave a Comment