library(ggplot2)
library(dplyr)
library(tidyr)
# load the mtcars dataset
data(mtcars)
# create a new variable with the average of mpg and wt columns
mtcars$avg_mpg_wt <- rowMeans(mtcars[c("mpg", "wt")])
# stack the data and calculate proportions
mtcars_stack <- mtcars %>%
pivot_longer(cols = c("mpg", "wt", "avg_mpg_wt"), names_to = "variable", values_to = "value") %>%
group_by(cyl, variable) %>%
summarise(total = sum(value),
proportion = value / total) %>%
ungroup()
# create a stacked bar chart with facets
ggplot(mtcars_stack, aes(x = cyl, y = proportion, fill = variable)) +
geom_bar(stat = "identity", color = "black", size = 0.25) +
scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
labs(title = "Stacked Bar Chart: Average mpg and wt by Cylinder Count",
x = "Cylinder Count",
y = "Proportion",
fill = "Variable") +
theme_minimal() +
theme(plot.title = element_text(face = "bold", size = 16, hjust = 0.5),
axis.title = element_text(face = "bold", size = 12),
legend.position = "bottom",
legend.title = element_text(face = "bold", size = 12),
legend.text = element_text(size = 10)) +
guides(fill = guide_legend(nrow = 1))