ggplot2雨图(rainingplot)函数问题:调整间距与分类着色
解决R包rainplot_fig函数的两个问题
1. 调整stat_halfeye与箱线图的间距
核心是修改stat_halfeye的justification参数:
- 该参数控制横向halfeye图形相对于分类轴(y轴)的对齐位置,当参数为负数时,图形会向远离箱线图的方向偏移;数值绝对值越大,两者间距越宽。
- 可配合
width参数调整halfeye本身的宽度,避免间距调整后图形重叠或过窄。
2. 按分类给分布图添加颜色
需要在ggplot的全局映射或stat_halfeye的局部映射中,将fill(填充色)绑定到分类变量var2,再通过scale_fill_manual指定对应分类的颜色。
修改后的完整函数代码
#' Exploratory Data Analysis: Rainingplot #' #' This function creates a rainingplot to represent continuous data. It uses a classification variable #' @param db D.B_Final databse obtained in the incorporation - data step. #' @param var1 Dependent variable. It must be a continuous variable #' @param var2 Classification variable #' @param fill_colors Named vector specifying colors for each category in var2 (e.g., c("Variante 1" = "#FF0000", "Variante 2" = "#00FF00", "Variante 3" = "#0000FF")) #' @param halfeye_justification Numeric value to adjust spacing between halfeye and boxplot (default: -0.3, increase absolute value for wider spacing) #' @return A rainingplot classified by the `var2` argument. #' @export #' rainplot_fig<-function(db,var1,var2, fill_colors = NULL, halfeye_justification = -0.3){ # 初始化ggplot,绑定fill到分类变量 fig<-ggplot2::ggplot(db, ggplot2::aes({{var1}}, {{var2}}, fill = {{var2}})) + # 调整halfeye的间距与显示样式 ggdist::stat_halfeye(adjust = .5, width = .7, .width = 0, justification = halfeye_justification, point_colour = NA) + # 箱线图设为白色避免遮挡halfeye颜色 ggplot2::geom_boxplot(width = .2, outlier.shape = NA, fill = "white") + # 散点用灰色弱化,避免干扰主体图形 ggplot2::geom_jitter(height =0.05,size=.9,width = 1, alpha = .3, color = "gray50") + ggplot2::theme_minimal() + ggplot2::theme(legend.position = "bottom") # 应用用户自定义颜色(若提供) if(!is.null(fill_colors)){ fig <- fig + ggplot2::scale_fill_manual(values = fill_colors) } return(fig) }
使用示例
# 构造测试数据集 db <- data.frame( var1 = rnorm(300), var2 = rep(c("Variante 1", "Variante 2", "Variante 3"), each = 100) ) # 指定分类对应颜色 custom_colors <- c("Variante 1" = "#E63946", "Variante 2" = "#457B9D", "Variante 3" = "#1D3557") # 生成带自定义颜色和调整后间距的雨图 rainplot_fig(db, var1, var2, fill_colors = custom_colors, halfeye_justification = -0.4)
关键修改说明
- 间距控制:新增
halfeye_justification参数,让用户可灵活调整halfeye与箱线图的间距,默认值-0.3比原代码的-0.2间距稍宽,可按需修改。 - 颜色设置:全局绑定
fill={{var2}}实现halfeye按分类着色,箱线图设为白色避免遮挡;新增fill_colors参数支持自定义分类颜色,未指定时使用ggplot默认配色。
内容的提问来源于stack exchange,提问作者Francisco
相关产品推荐
相关产品推荐

