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

R语言中调整visreg结合ggplot2的线型与y轴范围求助

lmer模型残差图的y轴范围与线条样式调整方案

1. 调整y轴范围

要限制y轴下限到-5且不截断上方数据,使用coord_cartesian()而非ylim()(后者会过滤超出范围的数据点)。修改后的代码如下:

# 保存基础绘图对象
p <- visreg(modII, "PC2", by = "Vegetation_type", line.par = list(col = 'black'), band = F, 
       gg = T) + 
  theme_minimal() + 
  geom_point(size = 1) + ylab("")

# 仅限制y轴下限为-5,上限自动适配数据
p <- p + coord_cartesian(ylim = c(-5, NA))

2. 设置子图线条样式(仅中间子图为实线)

先确认Vegetation_type的类别水平顺序,再通过手动映射线型实现需求:

步骤1:查看类别水平

# 查看Vegetation_type的所有类别及排序
levels(geral$Vegetation_type)

假设输出为["Forest", "Grassland", "Wetland"],其中Grassland对应中间子图的类别。

步骤2:映射并设置线型

# 找到绘图中的线条图层,添加Vegetation_type的线型映射
line_layer <- which(sapply(p$layers, function(x) class(x$geom)[1] == "GeomLine"))
p$layers[[line_layer]]$mapping <- aes(x = x, y = visregFit, linetype = Vegetation_type)

# 手动指定每个类别的线型:中间类别用实线,其余用虚线
p <- p + scale_linetype_manual(
  values = setNames(
    c("dashed", "solid", "dashed"),  # 顺序与levels输出的类别顺序对应
    levels(geral$Vegetation_type)
  )
)

完整代码整合

modII <- lmer(Isoprene_microgC_g_g ~ PC2 * Vegetation_type + (1|Spp.1), 
  data = geral)

# 生成基础绘图
p <- visreg(modII, "PC2", by = "Vegetation_type", line.par = list(col = 'black'), band = F, 
       gg = T) + 
  theme_minimal() + 
  geom_point(size = 1) + ylab("")

# 调整y轴范围
p <- p + coord_cartesian(ylim = c(-5, NA))

# 设置线条样式
line_layer <- which(sapply(p$layers, function(x) class(x$geom)[1] == "GeomLine"))
p$layers[[line_layer]]$mapping <- aes(x = x, y = visregFit, linetype = Vegetation_type)
p <- p + scale_linetype_manual(
  values = setNames(
    c("dashed", "solid", "dashed"),
    levels(geral$Vegetation_type)
  )
)

# 输出图形
print(p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:05:10