使用add_pvalue()时ggplot2条形图无法着色的问题求助
fill=Group后add_pvalue()报错'Group' not found 在使用ggplot2绘制类似PRISM的彩色条形图时,在aes()中加入fill=Group实现分组着色后,调用add_pvalue()函数出现以下错误:
Error:
! Problem while computing aesthetics.
i Error occurred in the 3rd layer.
Caused by error inFUN():
! object 'Group' not found
Runrlang::last_trace()to see where the error occurred.
测试验证:移除fill=Group可正常生成黑白条形图并显示p值;移除add_pvalue()可正常生成彩色条形图。
解决方案
方法1:在add_pvalue()中禁用美学继承
在add_pvalue()函数中添加inherit.aes = FALSE,阻止该图层继承全局的fill=Group映射,避免因数据不匹配报错。
修改后的完整代码:
# 1 - 转换为数据框 df <- as.data.frame(Data3) # 2 - 计算各组的均值和标准差 # 2.1 - 定义统计汇总函数 data_summary <- function(data, varname, groupnames) { require(plyr) summary_func <- function(x, col) { c( mean = mean(x[[col]], na.rm = TRUE), sd = sd(x[[col]], na.rm = TRUE) ) } data_sum <- ddply(data, groupnames, .fun = summary_func, varname ) data_sum <- rename(data_sum, c("mean" = varname)) return(data_sum) } # 2.2 - 生成汇总数据 df3 <- data_summary(Data3, varname = "Luminescence", groupnames = c("Group") ) # 3 - 计算p值并设置位置 df_p_val <- rstatix::t_test(Data3, Luminescence ~ Group, ref.group = "OSCC alone") %>% rstatix::add_xy_position() # 4 - 绘制条形图并添加p值 p <- ggplot(df3, aes(x = Group, y = Luminescence, fill = Group)) + geom_bar(stat = "identity", position = position_dodge(), width = 0.5) + geom_errorbar(aes(ymin = Luminescence - sd, ymax = Luminescence + sd), width = 0.1, position = position_dodge(.9) ) + theme_prism() + theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8), axis.title = element_text(size = 10)) + scale_y_continuous(expand = c(0, 0), limits = function(x) { c(0, ceiling(max(x) * 1.1)) }) + scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) + add_pvalue(df_p_val, label = "p.adj.signif", inherit.aes = FALSE) # 禁用美学继承 p
方法2:仅在需要的图层中设置fill映射
不在ggplot全局aes()中设置fill=Group,只在geom_bar()中单独指定该映射,这样后续图层不会继承不必要的美学规则。
修改后的核心代码片段:
p <- ggplot(df3, aes(x = Group, y = Luminescence)) + # 全局aes移除fill geom_bar(aes(fill = Group), stat = "identity", position = position_dodge(), width = 0.5) + # 单独在条形图层设置fill geom_errorbar(aes(ymin = Luminescence - sd, ymax = Luminescence + sd), width = 0.1, position = position_dodge(.9) ) + # 其余设置保持不变 theme_prism() + theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8), axis.title = element_text(size = 10)) + scale_y_continuous(expand = c(0, 0), limits = function(x) { c(0, ceiling(max(x) * 1.1)) }) + scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) + add_pvalue(df_p_val, label = "p.adj.signif") p
错误原因说明
当在ggplot全局aes()中设置fill=Group时,所有后续图层(包括add_pvalue()生成的p值标签图层)都会默认继承该美学映射。但add_pvalue()使用的df_p_val数据框中并不包含Group列,因此会触发object 'Group' not found的错误。通过上述两种方法,可以避免图层继承不必要的美学规则,解决报错问题。
内容的提问来源于stack exchange,提问作者Miguel

