##Design a Waffle chart representing distribution of occupation in urban vs rural areas
#Step 1:Install Required packages
#Step 2:Load libraries
Warning: package 'ggplot2' was built under R version 4.5.3
Attaching package: 'dplyr'
The following objects are masked from 'package:stats':
filter, lag
The following objects are masked from 'package:base':
intersect, setdiff, setequal, union
#Step 3: Create Data (Total = 100)
urban <- data.frame (
category = c ("Service" ,"Business" ,"Professional" ,"Labor" ,"Others" ),
value = c (30 , 25 , 20 , 15 , 10 )
)
rural <- data.frame (
category = c ("Agriculture" ,"Labor" ,"Small Business" ,"Service" ,"Others" ),
value = c (40 , 25 , 15 , 10 , 10 )
)
#Step 4: Function to Create Waffle Grid
create_waffle <- function (data, title_name) {
waffle_data <- data %>%
uncount (value) %>%
mutate (id = row_number (),
x = (id - 1 ) %% 10 ,
y = (id - 1 ) %/% 10 )
ggplot (waffle_data, aes (x, y, fill = category)) +
geom_tile (color = "white" ) +
coord_equal () +
scale_y_reverse () +
labs (title = title_name, fill = "Occupation" ) +
theme_minimal () +
theme (axis.title = element_blank (),
axis.text = element_blank (),
panel.grid = element_blank ())
}
#Step 5: Plot Charts
create_waffle (urban, "Urban Occupation Distribution" )
create_waffle (rural, "Rural Occupation Distribution" )
#step 6:Create Combined Data
data <- data.frame (
Area = rep (c ("Urban" , "Rural" ), each = 5 ),
category = c ("Service" ,"Business" ,"Professional" ,"Labor" ,"Others" ,
"Agriculture" ,"Labor" ,"Small Business" ,"Service" ,"Others" ),
value = c (30 ,25 ,20 ,15 ,10 ,
40 ,25 ,15 ,10 ,10 )
)
#Step 7: Expand Data (Create Waffle Blocks)
waffle_data <- data[rep (1 : nrow (data), data$ value), ]
waffle_data$ id <- 1 : nrow (waffle_data)
#Step 8: Create Grid Positions
waffle_data <- waffle_data %>%
group_by (Area) %>%
mutate (
x = (row_number () - 1 ) %% 10 ,
y = (row_number () - 1 ) %/% 10
)
#Step 9: Urban vs Rural (Versus Bar Chart)
ggplot (waffle_data, aes (x, y, fill = category)) +
geom_tile (color = "white" ) +
coord_equal () +
scale_y_reverse () +
facet_wrap (~ Area) +
labs (title = "Waffle Chart: Urban vs Rural Occupation Distribution" ,
fill = "Occupation" ) +
theme_minimal () +
theme (
axis.title = element_blank (),
axis.text = element_blank (), panel.grid = element_blank ()
)