在R ggplot中为X轴(因子水平)添加间隔及替换统计星号为柱状标注
解决方案
1. 修复X轴刻度问题
报错原因是hrs为因子类型,而scale_x_continuous仅适用于连续数值变量,两者不兼容。提供两种解决方法:
方法一:将hrs转换为数值型变量
先把数据中的hrs从因子转为数值,再用scale_x_continuous设置刻度:
# 取消分组并转换hrs类型 df02_EC_01 <- df02_EC_01 %>% ungroup() %>% mutate(hrs = as.numeric(as.character(hrs))) # 重新绘图 plot01 <- ggplot(df02_EC_01, aes(x=hrs, y=Vol_mm3, fill=Temp, color=Temp)) + geom_dotplot(binaxis = "y", stackdir = "centerwhole", alpha = .5, dotsize = .3, method = "histodot", binwidth = 1, stackratio = 1, position = "dodge", binpositions="all") + geom_boxplot(varwidth = T, size= .5, coef=500, alpha=.5) + labs(title = "Decalcification Process with EDTA", x = "Hours", y = "Mineralized tissue (mm3)") + theme(plot.title = element_text(hjust = 0.5)) + stat_compare_means(aes(group=Temp), label = "p.signif") + scale_x_continuous(breaks = seq(0, 72, by = 12), labels = seq(0, 72, by = 12), limits = c(0,72)) + # 可选:限制X轴范围到72 ylim(0,30)
方法二:保留因子类型,用scale_x_discrete调整刻度
若需保留hrs的因子属性,可指定要显示的刻度标签:
plot01 <- ggplot(df02_EC_01, aes(x=hrs, y=Vol_mm3, fill=Temp, color=Temp)) + geom_dotplot(binaxis = "y", stackdir = "centerwhole", alpha = .5, dotsize = .3, method = "histodot", binwidth = 1, stackratio = 1, position = "dodge", binpositions="all") + geom_boxplot(varwidth = T, size= .5, coef=500, alpha=.5) + labs(title = "Decalcification Process with EDTA", x = "Hours", y = "Mineralized tissue (mm3)") + theme(plot.title = element_text(hjust = 0.5)) + stat_compare_means(aes(group=Temp), label = "p.signif") + scale_x_discrete(breaks = c("0","12","24","48","72"), # 指定显示的因子水平 labels = c("0","12","24","48","72")) + ylim(0,30)
2. 替换显著性星号为柱状连线标注
使用ggsignif包的geom_signif生成带连线的显著性标注,替代stat_compare_means的星号:
步骤1:安装并加载ggsignif
install.packages("ggsignif") library(ggsignif)
步骤2:修改绘图代码
用geom_signif替换stat_compare_means,指定比较组与标注位置:
# 先确保hrs为数值型(参考方法一的转换) df02_EC_01 <- df02_EC_01 %>% ungroup() %>% mutate(hrs = as.numeric(as.character(hrs))) plot01 <- ggplot(df02_EC_01, aes(x=hrs, y=Vol_mm3, fill=Temp, color=Temp)) + geom_dotplot(binaxis = "y", stackdir = "centerwhole", alpha = .5, dotsize = .3, method = "histodot", binwidth = 1, stackratio = 1, position = "dodge", binpositions="all") + geom_boxplot(varwidth = T, size= .5, coef=500, alpha=.5) + labs(title = "Decalcification Process with EDTA", x = "Hours", y = "Mineralized tissue (mm3)") + theme(plot.title = element_text(hjust = 0.5)) + # 生成柱状显著性标注 geom_signif(comparisons = list(c("RT", "37C")), y_position = c(28,26,24,22,20), # 每个时间点的标注高度,可按需调整 x_position = c(0,12,24,48,72), # 对应时间点的X轴位置 map_signif_level = TRUE, # 显示显著性等级(如***、**) tip_length = 0.01) + scale_x_continuous(breaks = seq(0, 72, by = 12), labels = seq(0, 72, by = 12)) + ylim(0,30)
若需显示具体p值而非等级,可调整参数:
geom_signif(comparisons = list(c("RT", "37C")), y_position = c(28,26,24,22,20), x_position = c(0,12,24,48,72), map_signif_level = FALSE, test = "t.test", # 根据你的统计方法调整 tip_length = 0.01)
内容的提问来源于stack exchange,提问作者Marcello
相关产品推荐
相关产品推荐

