如何在R中将两组数据生成的圆形百分比图表叠加展示?
实现方案
要将两组数据的圆形放在同一张画布对比,核心是对齐同类别(Type)的X轴位置,同时避免圆形互相遮挡,具体实现步骤和代码如下:
前置依赖
需要用到ggforce包的geom_circle图层,未安装的话先运行:
install.packages("ggforce")
完整代码
# 加载所需包 library(dplyr) library(ggplot2) library(ggforce) # 构造基础组数据并新增分组标识 df_base <- structure(list(percents = c(52, 40, 34, 55, 48, 38, 17), label = c("Type 1", "Type 2", "Type 3", "Type 4", "Type 5", "Type 6", "Type 7")), class = "data.frame", row.names = c(NA, -7L)) %>% mutate(group = "基础组") # 构造B组数据并新增分组标识 df_b <- structure(list(percents = c(48, 60, 66, 45, 52, 62, 83), label = c("Type 1", "Type 2", "Type 3", "Type 4", "Type 5", "Type 6", "Type 7")), class = "data.frame", row.names = c(NA, -7L)) %>% mutate(group = "B组") # 合并数据并计算统一坐标 df_all <- bind_rows(df_base, df_b) %>% group_by(label) %>% # 取同类别两组的最大半径计算间距,避免相邻类别圆重叠 mutate(max_r = max(sqrt(percents))) %>% ungroup() %>% arrange(label) %>% # 所有类别统一计算X轴位置,保证同类别两组圆对齐 mutate(x = max_r + cumsum(lag(2 * max_r, default = 0))) %>% # 两组圆Y轴错开:基础组在上,B组在下,避免完全遮挡 mutate(y0 = ifelse(group == "基础组", sqrt(percents), -sqrt(percents))) # 绘图 ggplot(df_all) + # 圆形按分组区分颜色 geom_circle(aes(x0 = x, r = sqrt(percents), y0 = y0, color = group), size = 3) + # 百分比标签对应到各自圆心位置 geom_text(aes(x = x, y = y0, label = paste0(percents, "%"), size = percents), fontface = "bold", color = "#643291") + # 顶部保留统一的类别标签 geom_text(aes(x = x, y = 20, label = label), vjust = 0, fontface = "bold", color = "gray20", size = 3) + # 基础组引导线保留在上部 geom_segment(data = filter(df_all, group == "基础组"), aes(x = x, xend = x, y = sqrt(percents) + 3, yend = 18), color = "#643291", size = 2) + # 匹配原有配色:基础组灰色,B组黑色 scale_color_manual(values = c("基础组" = "gray", "B组" = "black")) + coord_equal() + # 调整Y轴范围适配上下两排圆 scale_y_continuous(limits =c(-25, 25)) + scale_size_continuous(range = c(4, 8)) + theme_void() + # 保留分组图例 theme(legend.position = "top", legend.title = element_blank()) + labs(title ='2018年两组数据对比')
可选调整
如果想要同类别圆形重叠展示,可以去掉Y轴偏移的逻辑,同时给圆形增加透明度:
- 把
mutate(y0 = ifelse(...))改成mutate(y0 = sqrt(percents)) - 在
geom_circle参数里增加alpha=0.5即可
内容的提问来源于stack exchange,提问作者BR27
相关产品推荐
相关产品推荐

