【问题标题】:positioning geom_boxplot to top of figure将 geom_boxplot 定位到图的顶部
【发布时间】:2020-11-11 04:51:28
【问题描述】:

我希望能够绘制一个包含对 ggplot() 的 geom_boxplot()、geom_histogram() 和 geom_rug() 调用的图形。我不确定如何在不硬编码ymaxymin 值的情况下将geom_boxplot() 输出的位置移动到图的顶部。很高兴知道如何让 ggplot 根据 geom_histogram 的binwidth 的特定参数的效果的结果来计算这个结果。

例如,给定这些数据:

set.seed(42)
df <- data.frame(
  counts=ceiling(runif(n = 100, min = 100, max = 1000)),
  sampleID=paste0("sample-",seq(1,100)))

还有这个功能:

ggplot(df, aes(counts)) +
  geom_histogram(binwidth = 10) +
  geom_rug(sides = "b") +
  geom_boxplot() +
  theme(panel.grid = element_blank())

输出是沿着图底部的箱线图:

但是,我希望它位于直方图的所有垂直条之上。在这种特殊情况下,我可能会手动更改图像,因为我现在知道 y 的最大值是多少:

ggplot(df, aes(counts)) +
  geom_histogram(binwidth = 10) +
  geom_rug(sides = "b") +
  geom_boxplot(ymin=4.5, ymax=5) +
  scale_y_continuous(limits = c(0, 5), breaks = c(0,2,4)) +
  theme(panel.grid = element_blank())

不过,如果有人能指导我如何在无需手动调整的情况下创建这种类型的情节,我将不胜感激。

感谢您的考虑

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这样的?

    p <- ggplot(df, aes(counts)) +
      geom_histogram(binwidth = 10) +
      geom_rug(sides = "b") +
      scale_y_continuous(limits = c(0, 5), breaks = c(0,2,4)) +
      theme(panel.grid = element_blank())
    
    ub <- max(ggplot_build(p)$data[[1]]$count)
    p + geom_boxplot(ymin = ub + 0.5, ymax = ub + 1, y = ub + 0.75)
    

    请注意,如果您只设置了yminymax,则晶须在y = 0 处是断开的线,这可能不是您想要的。

    您也可以映射y,而不是最后一行,如下所示:

    p + geom_boxplot(aes(y = upper + 0.5))
    

    然后width控制框的大小。

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 2019-07-10
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多