求ggplot2绘制上下均带圆角堆叠柱状图的有效替代方案
替代ggchicklet生成上下带圆角的堆叠柱状图方案
可以使用ggforce结合数据预处理实现需求,核心思路是拆分堆叠柱的不同部分(底部块、中间块、顶部块),分别绘制带圆角的底部/顶部块和无圆角的中间块,模拟ggchicklet的效果:
步骤1:加载依赖包
library(ggplot2) library(ggforce) library(dplyr)
步骤2:预处理数据
计算每个堆叠块的起始/结束位置,并标记是否为柱的底部或顶部块:
# 以mtcars数据集为例,按cyl和gear分组统计计数 stack_data <- mtcars %>% count(cyl, gear) %>% arrange(cyl, gear) %>% group_by(cyl) %>% mutate( y_start = cumsum(n) - n, # 堆叠块的起始y值 y_end = cumsum(n), # 堆叠块的结束y值 is_bottom = row_number() == 1, # 标记是否为柱的底部块 is_top = row_number() == n() # 标记是否为柱的顶部块 ) %>% ungroup()
步骤3:绘制带圆角的堆叠柱状图
分别绘制底部(带底部圆角)、中间(无圆角)、顶部(带顶部圆角)的堆叠块:
ggplot(stack_data, aes(x = factor(cyl))) + # 绘制底部堆叠块,仅保留底部圆角 geom_rounded_rect( data = filter(stack_data, is_bottom), aes( xmin = as.numeric(x) - 0.4, xmax = as.numeric(x) + 0.4, ymin = y_start, ymax = y_end, fill = factor(gear) ), radius = unit(5, "pt"), sides = "bottom" ) + # 绘制中间堆叠块,无圆角 geom_rect( data = filter(stack_data, !is_bottom & !is_top), aes( xmin = as.numeric(x) - 0.4, xmax = as.numeric(x) + 0.4, ymin = y_start, ymax = y_end, fill = factor(gear) ) ) + # 绘制顶部堆叠块,仅保留顶部圆角 geom_rounded_rect( data = filter(stack_data, is_top), aes( xmin = as.numeric(x) - 0.4, xmax = as.numeric(x) + 0.4, ymin = y_start, ymax = y_end, fill = factor(gear) ), radius = unit(5, "pt"), sides = "top" ) + # 调整标签和主题 labs(x = "气缸数", y = "计数", fill = "档位") + theme_minimal()
额外说明
- 通过
sides参数控制圆角位置,bottom仅生成底部圆角,top仅生成顶部圆角;若需要每个堆叠块上下都带圆角,可去掉is_bottom/is_top过滤,对所有块使用sides = "topbottom" radius参数可调整圆角弧度大小,支持pt、mm等单位
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

