当我运行此代码时,我只能获得多个百分比,是否缺少某些内容或我的代码中有错误?
我期望发生的情况:创建一个堆叠百分比条形图,并在图上显示百分比文本,以便更轻松地可视化百分比差异,以便于使用...
任何帮助将不胜感激:)
想要发生的事情:在图表上显示单个%文本并显示它 实际发生了什么:显示了很多百分比,我不知道为什么会发生这种情况或如何补救
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")