从这个数据框
df <- data.frame(cat=c(rep("X", 20),rep("Y", 20), rep("Z",20)),
value=c(runif(20),runif(20)*100, rep(0, 20)),
var=rep(LETTERS[1:5],12))
Run Code Online (Sandbox Code Playgroud)
我想创建多面箱线图。
library(ggplot2)
p1 <- ggplot(df, aes(var,value)) + geom_boxplot() + facet_wrap(~cat, scale="free")
p1
Run Code Online (Sandbox Code Playgroud)
结果在美观上并不令人满意,因为它将空面板的 y 轴中心为零。我想将所有 y 尺度从零开始。我从之前的问题中尝试了几个答案:
p1 + scale_y_continuous(expand = c(0, 0)) # not working
p1 + expand_limits(y = 0) #not working
p1 + scale_y_continuous(limits=c(0,NA)) ## not working
p1 + scale_y_continuous(limits=c(0,100)) ## partially working, but defeats scale="free"
p1 + scale_y_continuous(limits=c(0,max(df$value))) ## partially working, see above
p1 + scale_y_continuous(limits=c(0,max(df$value))) + expand_limits(y = 0)## partially working, see above
Run Code Online (Sandbox Code Playgroud)
一种解决方案可能是用非常小的值替换零,但也许您可以找到更直接的解决方案。谢谢。
一个更简单的解决方案是将函数作为限制参数传递:
p1 <- ggplot(df, aes(var,value)) + geom_boxplot() + facet_wrap(~cat, scale="free") +
scale_y_continuous(limits = function(x){c(0, max(0.1, x))})
Run Code Online (Sandbox Code Playgroud)
该函数将每个方面自动计算的限制作为x参数,您可以在其中对它们应用任何转换,例如选择 0.1 和真实最大值之间的最大值。
但结果仍需扩大规模。