![](/img/trans.png)
[英]Using secondary y-axis in ggplot2 with different scale factor when using facet_wrap
[英]Facet_wrap and scale="free" unexpectedly centers y-axis at zero in ggplot2
从这个数据帧
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))
我想创建多面箱线图。
library(ggplot2)
p1 <- ggplot(df, aes(var,value)) + geom_boxplot() + facet_wrap(~cat, scale="free")
p1
结果在美学上令人不满意,因为它使空面板的 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
一种解决方案可能是用非常小的值替换零,但也许您可以找到更直接的解决方案。 谢谢你。
这可能有点geom_blank()
,但您可以使用geom_blank()
来帮助设置轴尺寸。 例如:
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))
# Use this data frame to set min and max for each category
# NOTE: If the value in this DF is smaller than the max in df it will be overridden
# by the max(df$value)
axisData <- data.frame(cat = c("X", "X", "Y", "Y", "Z", "Z"),
x = 'A', y = c(0, 1, 0, 100, 0, 1))
p1 <- ggplot(df, aes(var,value)) +
geom_boxplot() +
geom_blank(data = axisData, aes(x = x, y = y)) +
facet_wrap(~cat, scale="free")
p1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.