如何使用ggplot2绘制指定半月亮图?求对应实现脚本
ggplot2 实现学术文章半月亮图模板脚本
所需依赖包
首先确保安装并加载以下R包:
install.packages(c("ggplot2", "ggforce", "dplyr")) library(ggplot2) library(ggforce) library(dplyr)
构造示例数据
模拟目标图中的数据结构,包含类别、分组和对应数值:
set.seed(123) data <- tibble( category = rep(c("处理1", "处理2", "处理3", "处理4"), each = 2), group = rep(c("A组", "B组"), 4), value = sample(20:80, 8) ) %>% mutate(y_pos = as.numeric(factor(category)) + ifelse(group == "A组", -0.15, 0.15))
核心绘图代码
通过ggforce::geom_arc_bar实现半月亮(半圆弧形)效果,搭配主题调整适配学术图风格:
ggplot(data, aes(x0 = 0, y0 = y_pos, r0 = 0, r = 0.4, start = 0, end = pi)) + # 绘制半月亮弧形,填充色映射数值 geom_arc_bar(aes(fill = value), color = "black") + # 添加数值标签 geom_text(aes(x = 0.5, y = y_pos, label = paste0(value, "%")), size = 3.5) + # 添加类别标签 geom_text(data = distinct(data, category, y_pos = as.numeric(factor(category))), aes(x = -0.6, y = y_pos, label = category), size = 4) + # 添加分组标签 geom_text(data = distinct(data, group), aes(x = 0, y = max(y_pos) + 0.5, label = group), position = position_dodge(0.3), size = 4) + # 设置颜色渐变(可根据文章需求调整) scale_fill_viridis_c(option = "plasma", name = "相对值") + # 调整坐标系与主题 coord_fixed(xlim = c(-1, 1), ylim = c(0.5, 4.5)) + theme_minimal() + theme( axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank(), legend.position = "bottom", plot.margin = margin(10, 10, 10, 10) )
参数调整说明
- 调整
r参数可以改变半月亮的大小; - 修改
start和end的值可以切换半圆方向(如start = pi, end = 2*pi得到下半圆); - 通过
scale_fill_*系列函数替换配色方案,匹配文章中的颜色风格; - 调整
xlim、ylim和标签位置,适配不同数量的类别和分组。
内容的提问来源于stack exchange,提问作者Mateus Piza
相关产品推荐
相关产品推荐

