代码之家  ›  专栏  ›  技术社区  ›  Richie Cotton Joris Meys

如何为不同的面设置不同的比例限制?

  •  25
  • Richie Cotton Joris Meys  · 技术社区  · 14 年前

    一些示例数据:

    dfr <- data.frame(
      x = rep.int(1:10, 2),
      y = runif(20),
      g = factor(rep(letters[1:2], each = 10))
    )
    

    有两个方面的简单散点图:

    p <- ggplot(dfr, aes(x, y)) + 
      geom_point() +
      facet_wrap(~ g, scales = "free_y")
    

    我可以为所有面板设置轴限制。

    p + scale_y_continuous(limits = c(0.2, 0.8))
    

    (或者像这样的包装 ylim )

    但是如何为不同的方面设置不同的轴限制呢?

    这样做的方式是将一个列表传递给这个参数,例如。,

    p + scale_y_continuous(limits = list(c(0.2, 0.8), c(0, 0.5)))
    

    不幸的是,这只是在ggplot2的情况下抛出了一个错误。

    编辑:

    这是部分破解。如果要扩展刻度范围,则可以向数据集中添加列以指定限制,然后使用 geom_blank .

    修改的数据集:

    dfr <- data.frame(
      x = rep.int(1:10, 2),
      y = runif(20),
      g = factor(rep(letters[1:2], each = 10)),
      ymin = rep(c(-0.6, 0.3), each = 10),
      ymax = rep(c(1.8, 0.5), each = 10)
    )
    

    更新的绘图:

    p + geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax))
    

    现在天平不同了,左手的天平是对的。不幸的是,右手比例尺没有收缩,因为它需要为点数腾出空间。

    如果有帮助的话,我们现在可以将问题重新表述为“是否可以在不重新计算比例尺和不显式调用 scale_y_continuous ?"

    2 回复  |  直到 14 年前
        1
  •  6
  •   Gavin Simpson    14 年前

    我认为这在ggplot2中是不可能的。这个 discussion 从一月份开始,这个问题就在考虑之中。

        2
  •  0
  •   Community Neeleshkumar S    7 年前

    若要缩小左侧绘图上的比例,请删除位于范围之外的点。例如,这将使右侧绘图上的y比例减小到0到0.5之间的值:

    p <- ggplot(dfr, aes(x, y)) +   
         geom_point(subset=.(g == "a" | (y > 0 & y <.5))) +
         geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax)) +
         facet_wrap(~ g, scales = "free_y")
    

    question .