ggplot堆叠条形图转堆叠面积图失败求助:空图问题排查
堆叠面积图无法正常显示的问题排查与解决
我原本用以下代码绘制堆叠条形图完全正常:
ggplot(data_frame, aes(x = year, y = percent, fill = reorder(type, desc(percent)), label = round(percent, digits=2))) + geom_bar(stat = "identity") + geom_text(size = 3, position = position_stack(vjust = 0.5))
尝试转换为堆叠面积图时,用了这段代码,结果图表为空或无法正常显示:
ggplot(data_frame, aes(x=year, y=percent, fill=as.factor(type))) + geom_area()
我的数据框结构如下:
structure(list(year = c(2012, 2013, 2013, 2014, 2014, 2015, 2015, 2015, 2016, 2016, 2016, 2017, 2017, 2017, 2018, 2018, 2018, 2019, 2019, 2019, 2020, 2020, 2020, 2021, 2021, 2021, 2022, 2022, 2022 ), type = c("Blue", "Red", "Blue", "Red", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue", "Red", "Yellow", "Blue"), percent = c(1, 0.822493861837742, 0.177506138162258, 0.890831469712102, 0.109168530287897, 0.813387070409725, 0.0497778071288365, 0.136835122461439, 0.864261238604485, 0.036537301512893, 0.0992014598826223, 0.869551858365865, 0.0555953345546625, 0.0748528070794728, 0.830539033602976, 0.075436440035225, 0.0940245263617988, 0.775315022945149, 0.0633554986887996, 0.161329478366051, 0.601100639265675, 0.254061406486953, 0.144837954247372, 0.630357987198663, 0.203272744842328, 0.166369267959009, 0.660638396593096, 0.174442088167586, 0.164919515239318 )), row.names = c(NA, -29L), class = "data.frame")
问题原因
问题出在数据完整性和排序逻辑上:
geom_area要求每个x轴值(此处为year)对应的所有分组(type)都有数据记录。你的数据中2012年只有Blue类型,缺少Red和Yellow的记录,导致无法形成连续的面积区域。- 原始数据未按
year和type排序,ggplot绘制堆叠面积图时需要数据按分组和x轴顺序排列,否则会出现堆叠错误或空白。
修正后的代码
先补全缺失的type-year组合,将缺失的percent设为0,再对数据排序,最后绘制堆叠面积图:
library(tidyr) library(ggplot2) # 补全缺失的type-year组合,缺失的percent填充为0 data_complete <- data_frame %>% complete(year, type, fill = list(percent = 0)) %>% # 按年份和类型排序 arrange(year, type) # 绘制堆叠面积图(可选添加数值标签) ggplot(data_complete, aes(x = year, y = percent, fill = type)) + geom_area(position = "stack") + geom_text(aes(label = ifelse(percent > 0, round(percent, 2), "")), size = 3, position = position_stack(vjust = 0.5))
代码说明
complete(year, type)生成所有year和type的组合,fill = list(percent = 0)为缺失行补充0值,确保每个年份都有三种类型的数据。arrange(year, type)保证数据按年份和类型排序,让ggplot正确堆叠各区域。position = "stack"是geom_area的默认设置,显式写出更清晰;若需要百分比堆叠可替换为position = "fill"。
内容的提问来源于stack exchange,提问作者daviddupont
相关产品推荐
相关产品推荐

