library
(ggplot2)
library
(dplyr)
library
(tidyr)
data
(mtcars)
mtcars$avg_mpg_wt <-
rowMeans
(mtcars[
c
(
"mpg"
,
"wt"
)])
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
()
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))