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

使用ggpredict()与plot()时如何修改坐标轴颜色并添加刻度?

解决坐标轴颜色与刻度无效的问题

问题出在ggpredict的默认绘图主题会覆盖你自定义的theme设置,加上xlim/ylim的使用方式会导致坐标轴元素丢失,以下是修正方案:

核心修正点:

  • 直接基于ggpredict返回的数据构建ggplot,而非使用plot(ggpredict())生成的预设对象
  • 用coord_cartesian()替代xlim/ylim(),避免过滤数据导致坐标轴元素丢失
  • 在theme中明确设置坐标轴线条、刻度线、刻度文本的样式

修正后的完整代码:

# 获取模型预测结果
self_acc2 <- ggpredict(model1, "mean.self")

# 手动构建ggplot图层
self_acc <- ggplot() +
  # 添加原始数据散点
  geom_point(data = dat_excluded, aes(x = mean.self, y = mean.acc),
             alpha = 0.5, colour = "blue", shape = 1) + # shape用数字1代表空心圆,更符合ggplot规范
  # 添加ggpredict的拟合线
  geom_line(data = self_acc2, aes(x = x, y = predicted), size = 1) +
  # 可选:添加置信区间带
  geom_ribbon(data = self_acc2, aes(x = x, ymin = conf.low, ymax = conf.high), alpha = 0.2) +
  # 缩放坐标轴范围(不丢失数据元素)
  coord_cartesian(xlim = c(0, 9), ylim = c(0, 1)) +
  # 设置标签与标题
  xlab("Self-Rated Accuracy") +
  ylab("Mean accuracy") +
  ggtitle("Relationship Between Self-Rated Accuracy and Actual Accuracy of Health Understanding") +
  # 自定义主题样式
  theme_bw() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.background = element_blank(),
    # 坐标轴线条颜色与粗细
    axis.line = element_line(colour = "black", size = 0.8),
    # 坐标轴刻度线颜色与粗细
    axis.ticks = element_line(colour = "black", size = 0.6),
    # 坐标轴刻度文本颜色与大小
    axis.text = element_text(colour = "black", size = 10),
    # 坐标轴标签样式
    axis.title = element_text(colour = "black", size = 12),
    # 标题居中
    plot.title = element_text(colour = "black", size = 14, hjust = 0.5)
  )

# 输出图像
self_acc

为什么之前的设置无效?

  1. plot(ggpredict())生成的对象自带预设theme,你后续叠加的theme(axis.line=...)优先级低于预设,所以被覆盖
  2. xlim/ylim()会直接过滤掉超出范围的数据,包括坐标轴的刻度元素,改用coord_cartesian()只是缩放显示范围,不会删除元素
  3. 你之前只设置了axis.line,但没配置axis.ticks(刻度线)和axis.text(刻度文本),所以刻度不显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:06:04