ggplot中调整y轴刻度(5至-5)并移除数据点的技术问题
解决方案
1. 核心问题修正
你的代码存在两个关键问题:
- 仅设置了y轴刻度断点,但未指定轴的范围,导致y轴不会自动扩展到-5到5
stat_compare_means行末尾多了无效的+n,会引发语法错误
2. 移除指定范围数据点
如果需要移除y值在-5到5之间的所有数据点,可通过提前过滤数据集实现;若需求是移除超出该范围的点,只需调整过滤条件即可。
以下是完整修正代码:
library(ggplot2) library(ggsignif) library(scales) pd = position_dodge(width = 0.5) # 过滤数据:保留不在-5到5范围内的点(若要保留范围内点,将!去掉即可) dt_filtered <- dt[!(dt$value >= -5 & dt$value <=5), ] ggplot(dt, aes(fill=Treatment, y= value, x=variable)) + stat_boxplot(geom = "errorbar", width = 0.25, position = pd)+ geom_boxplot(width=0.4, position = pd, outlier.shape = NA)+ # 使用过滤后的数据绘制散点 geom_jitter(data = dt_filtered, position = position_jitterdodge(jitter.width = 0.2,jitter.height = 0.8,dodge.width=0.5), shape=21, size=0.3, alpha=0.3) + scale_fill_manual(values = c("#CF9FFF","#800080"))+ stat_compare_means(aes(group = Treatment),method = "anova", label = "p.signif", label.y = c(2.15,2.55,2.7,2.3,2.7,2.7),size=3.5, symnum.args = list(cutpoints = c(0,0.001, 0.01, 0.05, Inf), symbols=c("***","**","*","ns")))+ theme(axis.text.x = element_text(size = 10, colour = "black", face="bold"), axis.text.y = element_text(size = 10, colour = "black", face="bold"), legend.position = c(0.15, 0.05), legend.background = element_blank(), legend.direction = "horizontal", legend.title = element_blank(), legend.text = element_text(size = 9, face="italic", colour = "black")) + scale_y_continuous(breaks = seq(-5,5,1), labels = number_format(accuracy = 0.01), limits = c(-5, 5)) # 强制设置y轴范围
关键说明
limits = c(-5,5):强制y轴显示-5到5的范围,这是之前代码缺失的核心设置- 数据过滤:通过
dt_filtered精准筛选需要保留的点,可根据实际需求调整过滤条件 - 移除了语法错误的
+n,确保代码正常运行
内容的提问来源于stack exchange,提问作者Ikram Bashir
相关产品推荐
相关产品推荐

