如何在ggplot2的facet_wrap中调整Y轴:从0开始且适配组最大值
解决方法
方法一:使用ggplot2原生函数(无需额外包)
直接通过scale_y_continuous()的limits参数传入自定义函数,固定Y轴下限为0,上限为对应分面数据的最大值,无需设置scales="free_y",函数会自动为每个分面计算合适的上限:
library(ggplot2) library(dplyr) dat <- data.frame(date = c(1:5, 1:5), type = rep(c("A", "B"), each = 5), value = c(4500, 4800, 4600, 4900, 4700, 1500, 1510, 1500, 1400, 1390) ) dat %>% ggplot(aes(date, value, group = type)) + geom_line() + facet_wrap(~type) + scale_y_continuous(limits = function(x) c(0, max(x)))
这里limits = function(x) c(0, max(x))会对每个分面的Y轴数据范围x单独处理,强制下限为0,上限取该分面数据的最大值,完全匹配需求。
方法二:使用ggh4x包(更灵活的分面刻度控制)
如果需要更复杂的分面刻度自定义,可以用ggh4x包的facetted_pos_scales()函数,先安装加载包,再为每个分面单独设置Y轴范围:
# 首次使用时安装包 # install.packages("ggh4x") library(ggh4x) library(dplyr) # 计算每个分组的最大值 max_values <- dat %>% group_by(type) %>% summarise(max_val = max(value)) %>% tibble::deframe() dat %>% ggplot(aes(date, value, group = type)) + geom_line() + facet_wrap(~type) + facetted_pos_scales( y = list( type == "A" ~ scale_y_continuous(limits = c(0, max_values["A"])), type == "B" ~ scale_y_continuous(limits = c(0, max_values["B"])) ) )
这个方法适合需要为不同分面设置差异化刻度规则的场景,扩展性更强。
内容的提问来源于stack exchange,提问作者Andrea M
相关产品推荐
相关产品推荐

