【问题标题】:ggplot add geom (specifically geom_hline) which doesn't affect limitsggplot添加不影响限制的geom(特别是geom_hline)
【发布时间】:2020-01-21 07:11:38
【问题描述】:

只有当数据接近阈值时,我想在一些数据上绘制阈值。因此,我希望在我的阈值处有一条水平线,但如果尚未包含此值,则不要扩展 y 轴限制。由于我的数据是多面的,因此预先计算限制是不可行的,我正在为许多不同的数据集做这件事,所以会变得非常混乱。这个问题似乎在问同样的事情,但答案与我无关:ggplot2: Adding a geom without affecting limits

简单的例子。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length))+geom_point()+facet_wrap(~Species, scales = "free")+geom_hline(yintercept = 7)

这给了我

但我希望这个(在油漆中创建)限制不受geom_hline 的影响

reprex package (v0.3.0) 于 2020-01-21 创建

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以通过检查给定构面的最大 y 值是否超过阈值来自动执行此操作。

    threshold = 7
    iris %>% 
      ggplot(aes(Sepal.Width, Sepal.Length)) +
      geom_point() + 
      facet_wrap(~Species, scales = "free") + 
      geom_hline(data = . %>% 
                   group_by(Species) %>%  
                   filter(max(Sepal.Length, na.rm=TRUE) >= threshold), 
                 yintercept = threshold)
    

    【讨论】:

    • 可能还需要考虑 abline 低于每个方面的范围...
    • 不错!这应该是一种享受。对于我的用例,如果所有数据都在上面,那么我仍然希望看到这条线,所以这比不改变轴更好(尽管这不太可能,所以我不太担心)
    【解决方案2】:

    改编自这篇文章:

    How can I add a line to one of the facets?

    library(tidyverse)
    iris %>% 
      ggplot(aes(x = Sepal.Width, y = Sepal.Length)) +
      geom_point() + 
      facet_wrap(~Species, scales = "free") + 
      geom_hline(data = . %>% filter(Species != "setosa"), aes(yintercept = 7))
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2021-11-17
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多