You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggbreak的scale_y_break后Y轴异常,如何保留Y轴底部为0?

解决ggplot+ggbreak中Y轴底部固定为0且回归图异常的问题

问题背景

我的ggplot回归图包含多个0值,模型不允许负值,因此Y轴最低值设为0。但在最大x值处标准误(standard error)低于0,尝试用scale_y_break缩减离群点空间后,回归图上移、标准误低于0,Y轴整体混乱,且添加scale_y_break后对象无法再用常规ggplot调整ylim。

解决方案

方案1:手动控制回归预测范围,避免负值

先拟合模型并生成预测数据,强制将所有低于0的预测值和置信区间下限设为0,再用geom_line和geom_ribbon替代stat_smooth,最后添加Y轴断点:

library(ggplot2)
library(ggbreak)

x_values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
y_values <- c(40, 12, 11, 10, 9, 9, 9, 8, 7.5, 0, 0, 0, 1)
custom_data <- data.frame(x = x_values, y = y_values)

# 拟合线性模型并生成带置信区间的预测数据
lm_model <- lm(y ~ x, data = custom_data)
pred_data <- as.data.frame(predict(lm_model, interval = "confidence", newdata = custom_data))
pred_data$x <- custom_data$x

# 强制所有Y相关值不低于0
pred_data$lwr <- pmax(pred_data$lwr, 0)
pred_data$fit <- pmax(pred_data$fit, 0)

# 绘图
graph <- ggplot(custom_data, aes(x = x, y = y)) +
  geom_point(size = 2, colour= "blue") +
  # 绘制回归线和置信区间
  geom_line(aes(y = fit), data = pred_data, col = "black") +
  geom_ribbon(aes(ymin = lwr, ymax = upr), data = pred_data, alpha = 0.2, fill = "grey") +
  scale_y_continuous(breaks = seq(0, 50, 5)) +
  scale_y_break(c(30, 35)) +
  labs(x = "Distance à la source", y = "Nombre de colonies") +
  theme_classic()

graph

方案2:使用coord_break替代scale_y_break

ggbreak的coord_break能更稳定地控制坐标轴范围,避免scale_y_break导致的布局偏移,同时保留Y轴下限为0:

library(ggplot2)
library(ggbreak)

x_values <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
y_values <- c(40, 12, 11, 10, 9, 9, 9, 8, 7.5, 0, 0, 0, 1)
custom_data <- data.frame(x = x_values, y = y_values)

graph <- ggplot(custom_data, aes(x = x, y = y)) +
  geom_point(size = 2, colour= "blue") +
  stat_smooth(formula = y ~ x, method = "lm", col = "black", se = TRUE) +
  labs(x = "Distance à la source", y = "Nombre de colonies") +
  theme_classic() +
  # 设定Y轴范围和断点,直接固定下限为0
  coord_break(ylim = c(0, 45), breaks = c(30, 35)) +
  scale_y_continuous(breaks = seq(0, 50, 5))

graph

问题原因说明

scale_y_break会修改坐标轴的底层变换规则,导致stat_smooth的计算不再受原coord_cartesian的Y轴范围限制,进而出现标准误低于0、回归线偏移的问题。而手动控制预测值或使用coord_break,能确保Y轴下限始终为0,同时维持回归图的正确显示。

内容的提问来源于stack exchange,提问作者Iris15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 13:27:48