when i run this code i am only able to get multiple percentages, is there something im missing or have i got an error in my code?
what i expected to happen: create a stacked percentage bar plot with percentage text on the plot to make it easier to visualise the difference in the percentages for ease of use...
any help would be greatly appreciated:)
wanted to happen: have single % text on graph and display it what actaully happened: showed many percentages and i dont know why this has happened or how to remedy it
library(ggplot2)
# Calculate the sum of mpg for each cyl value
sum_mpg <- aggregate(mpg ~ cyl, mtcars, sum)
# Merge the sum_mpg back into the mtcars dataset
mtcars <- merge(mtcars, sum_mpg, by = "cyl", suffixes = c("", "_sum"))
# Calculate the percentage within each cyl value
mtcars$percentage <- mtcars$mpg / mtcars$mpg_sum
# Create the stacked bar chart with correct percentages displayed
ggplot(mtcars, aes(fill = as.factor(gear), y = percentage, x = as.factor(cyl))) +
geom_bar(position = "fill", stat = "identity") +
geom_text(aes(label = scales::percent(percentage)),
position = position_fill(vjust = 0.5), size = 4, color = "black") +
labs(title = 'MPG vs Cylinder with Gear Segmentation') +
ylab("Percentage") +
xlab("Cylinder") +
scale_fill_discrete(name = "Gear")
If you want to do this all 'inside' ggplot using only the unmodified mtcars
as input, you could do:
library(ggplot2)
ggplot(mtcars, aes(x = as.factor(cyl), fill = as.factor(gear),
y = ave(mpg, cyl, FUN = function(x) x/sum(x)))) +
geom_col(position = "fill") +
geom_text(aes(label = scales::percent(after_stat(y))),
stat = 'summary', fun = 'sum',
position = position_fill(vjust = 0.5), size = 4, color = "black") +
labs(title = 'MPG vs Cylinder with Gear Segmentation', x = 'Percentage',
y = 'Cylinder', fill = 'Gear')