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

R语言分组绘图如何为不同变量分别设置自定义纵轴取值范围

解决方案

你可以借助ggh4x包的facetted_pos_scales()函数为不同分面单独指定纵轴范围,调整后的代码如下:

首先安装加载所需依赖:

# 首次使用先安装包
install.packages("ggh4x")
install.packages("tidyverse")

library(tidyverse)
library(ggh4x)

完整绘图代码:

set.seed(123)
ID = rep(c("BAU","IMP","SGR","CR"), each=5000)
Time = rep (c(1:1000), each = 20)
data <- data.frame( ID, Time,  profits = runif(20000,0,1), Salinity= runif(20000,3,4), Logging=runif(20000,0.05,3))
DF <- data %>% 
  group_by(Time, ID) %>% 
  summarise(Sal = mean(Salinity), 
            Logg = mean(Logging), 
            profs = mean(profits)) %>% 
  gather(type, value, c(Sal, Logg, profs))

ggplot(DF, aes(x=Time, y = value, color =ID)) +
  geom_line(size=1) + 
  # 行按type分组、列按ID分组,纵轴允许自由范围
  facet_grid(type ~ ID, scales = "free_y") +
  # 为不同变量分面设置指定纵轴范围
  facetted_pos_scales(
    y = list(
      type == "profs" ~ scale_y_continuous(limits = c(0, 0.5)),
      type == "Sal" ~ scale_y_continuous(limits = c(0, 2)),
      type == "Logg" ~ scale_y_continuous(limits = c(0, 3))
    )
  ) +
  theme_classic() +  
  theme(legend.position="top")+ 
  labs(title ="Baseline experiment", x ="Seasonal time steps", y = "Value")

注意:你当前示例数据中Sal的均值范围在3~4之间,设置纵轴上限为2会导致这部分数据完全被截断不可见,实际使用时请根据真实数据调整范围。

如果不需要按ID分列展示,仅按变量分行,将分面代码替换为facet_wrap(~type, ncol = 1, scales = "free_y")即可,facetted_pos_scales部分无需修改即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:39:01