ggplot2分面离散X轴丢弃未用水平 按分组数设置分面宽度比例
分面宽度按X轴分组数自适应调整实现方法
原生facet_wrap()不支持分面尺寸随轴类别数量自动适配,以下两种方案都可以实现setosa分面宽度为其余品种1/2的效果:
方案1:无额外依赖,换用facet_grid()
核心是将分面函数替换为facet_grid(),同时开启X轴的自由尺度和自由空间参数,space = "free_x"会自动让X方向分面宽度和轴的类别数量成正比。
完整代码如下:
library(tidyverse) # 数据预处理(和原有逻辑一致) i2 <- iris %>% pivot_longer(-Species, names_to='parameter', values_to='measure') i2 <- i2[-which(i2$Species=='setosa' & i2$parameter=='Petal.Length'),] i2 <- i2[-which(i2$Species=='setosa' & i2$parameter=='Petal.Width'),] # 绘图 ggplot(i2, aes(x=parameter, y=measure, colour=parameter)) + geom_point() + facet_grid(. ~ Species, scales = "free_x", space = "free_x")
运行后三个分面宽度会自动按X轴类别数匹配为1:2:2,setosa分面宽度正好是另外两个品种的1/2。
方案2:用ggh4x包自定义分面比例(适配复杂场景)
如果需要保留facet_wrap()的使用习惯,或者需要更灵活的尺寸自定义,可以加载ggplot2扩展包ggh4x,通过force_panelsizes()手动指定分面宽度比例:
library(tidyverse) library(ggh4x) # 数据预处理逻辑不变 i2 <- iris %>% pivot_longer(-Species, names_to='parameter', values_to='measure') i2 <- i2[-which(i2$Species=='setosa' & i2$parameter=='Petal.Length'),] i2 <- i2[-which(i2$Species=='setosa' & i2$parameter=='Petal.Width'),] # 绘图 ggplot(i2, aes(x=parameter, y=measure, colour=parameter)) + geom_point() + facet_wrap(~Species, nrow=1, scales='free_x') + # 按分面顺序指定宽度比例 force_panelsizes(cols = c(1, 2, 2))
最终效果参考:
内容的提问来源于stack exchange,提问作者francoiskroll
相关产品推荐
相关产品推荐

