Build a circular bar plot to show percentage allocation of a government budget across sectors.
Step 1 : Load the required libraries
# install.packages("ggplot2")
# install.packages("dplyr")
library(ggplot2)
library(dplyr)
Step 2 : Load the required dataframe
# Sample Data from https://www.usaspending.gov/ (Simulated)
budget_data <- data.frame(
sector = c(
"Health Care",
"Defense",
"Education",
"Infrastructure",
"Social Welfare",
"Science & Technology",
"Environment",
"Transportation",
"Energy",
"Agriculture"
),
percentage = c(19, 26, 12, 8, 10, 6, 5, 7, 4, 3)
)
# Add id for each sector
budget_data <- budget_data %>%
arrange(desc(percentage)) %>%
mutate(id = row_number())
# Calculate the angle of each bar (to rotate labels accordingly)
number_of_bars <- nrow(budget_data)
angle <- 90 - 360 * (budget_data$id - 0.5) / number_of_bars # Calculate angle for labels
budget_data <- budget_data %>%
mutate(angle = angle,
hjust = ifelse(angle < -90, 1, 0), # Align labels properly
angle = ifelse(angle < -90, angle + 180, angle))
Step 3 : Create a circular bar plot
p <- ggplot(budget_data, aes(x = as.factor(id), y = percentage, fill = sector)) +
geom_bar(stat="identity", color = "black", alpha=0.85) +
ylim(-10, max(budget_data$percentage) + 10) + # expand limits for label space
coord_polar(start = 0) +
geom_text(aes(label = paste0(sector, "\n", percentage, "%"), y = percentage + 3, angle = angle, hjust = hjust),
size=4, color = "black", fontface = "bold") +
theme_minimal() +
theme(
axis.text = element_blank(),
panel.grid = element_blank(),
axis.title = element_blank(),
legend.position = "none",
plot.title = element_text(hjust = 0.5, face = "bold", size = 16)
) +
scale_fill_viridis_d(option = "plasma") +
ggtitle("Government Budget Percentage Allocation by Sector")
# Print the plot
print(p)
