【问题标题】:Facet_wrap and scale="free" unexpectedly centers y-axis at zero in ggplot2Facet_wrap 和 scale="free" 在 ggplot2 中意外地将 y 轴居中于零
【发布时间】:2020-03-02 17:16:01
【问题描述】:

来自这个数据框

 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 尺度。我尝试了这个earlier question的几个答案:

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

一种解决方案可能是将零替换为非常小的值,但也许您可以找到更直接的解决方案。谢谢。

【问题讨论】:

  • 似乎这可能是作为问题提交github.com/tidyverse/ggplot2/issues 的好候选人。但是您如何期望绘图为 Z 面板选择最大值 y 值?我不确定那里有明显的默认值。
  • 好点。也许到 max(df$value))?

标签: r ggplot2


【解决方案1】:

更简单的解决方案是将函数作为限制参数传递:

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))})

该函数将自动计算的限制作为x 参数的每个方面,您可以在其中对其应用任何转换,例如选择0.1 和真实最大值之间的最大值。

但结果仍需扩大规模。

【讨论】:

  • 接受这一点,因为它无需辅助数据框即可工作。谢谢。
【解决方案2】:

这可能有点麻烦,但您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2023-04-08
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多