1

I have some data that I would like to plot a threshold on, only if the data approaches the threshold. Therefore I would like to have a horizontal line at my threshold, but not extend the y axis limits if this value wouldn't have already been included. As my data is faceted it is not feasible to pre-calculate limits and I am doing it for many different data sets so would get very messy. This question seems to be asking the same thing but the answers are not relevant to me: ggplot2: Adding a geom without affecting limits

Simple example.

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)

which gives me

But I would like this (created in paint) where the limits have not been impacted by the geom_hline intended output

Created on 2020-01-21 by the reprex package (v0.3.0)

Sarah
  • 3,022
  • 1
  • 19
  • 40

2 Answers2

2

You can automate this by checking whether a given facet has a maximum y-value that exceeds the threshold.

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)
eipi10
  • 91,525
  • 24
  • 209
  • 285
  • Might need to think about the abline going below the range of each facet as well... – StupidWolf Jan 20 '20 at 23:09
  • Nice! This should work a treat. For my use case if all data was above then I would still want to see the line so this is even better than just not changing the axis (although that's very unlikely so I wasn't too concerned about it) – Sarah Jan 20 '20 at 23:23
1

Adapting from this post:

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))
cardinal40
  • 1,245
  • 1
  • 9
  • 11