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

如何为facet_grid双分面图设置独立Y轴范围与刻度?

解决facet_grid面板独立Y轴的报错问题

你碰到的Error in rlang::eval_tidy(x, layout) : object '3' not found错误,根源是因子取值的匹配方式错误:

  • 你用反引号包裹3(即`3`),R会把它当作一个待查找的对象名,而非因子gear的取值;
  • 而gear已经被转为因子类型,它的实际取值是字符串格式的"3"、"4"、"5",必须用字符串来匹配面板条件。

修正后的完整代码如下:

mtcars$gear <- as.factor(mtcars$gear)
mtcars$cyl <- as.factor(mtcars$cyl)

ggplot(mtcars , aes(x=mpg, y=wt, color=as.factor(cyl) )) +
  geom_point(size=3) +
  facet_grid(gear~cyl, scales = "free_y") +
  theme(legend.position="none") + 
  ggh4x::facetted_pos_scales(y = list(
    gear == "3" ~ scale_y_continuous(limits = c(0, 6), breaks = seq(0, 5, 2.5)),
    gear == "4" ~ scale_y_continuous(limits = c(0, 7), breaks = seq(0, 5, 3)),
    gear == "5" ~ scale_y_continuous(limits = c(0, 5), breaks = seq(0, 5, 1))
  ))

关键修改点:

  • 将所有条件中的gear == `3`替换为gear == "3"(4、5同理),用字符串匹配因子取值,让ggh4x能正确识别对应面板;
  • 保持其他参数不变,即可为每个gear行的面板设置独立的Y轴刻度和范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:40:01