rggplot2facet-wrapgeom-hline

geom_hline with multiple points and facet_wrap


i am trying to plot horizontal lines at specific points of my data. The idea is that i would like a horizontal line from the first value of equivalent iterations(i.e 0) at y intercept for each of my axis; SA, VLA, HLA. My question will become clearer with data.

iterations  subsets equivalent_iterations   axis    ratio1        ratio2
0              0                       0     SA     0.023569024 0.019690577
0              0                       0     SA     0.023255814 0.019830028
0              0                       0     VLA    0.025362319 0.020348837
0              0                       0     HLA    0.022116904 0.021472393
2              2                       4     SA     0.029411765 0.024911032
2              2                       4     SA     0.024604569 0.022838499
2              2                       4     VLA    0.026070764 0.022727273
2              2                       4     HLA    0.027833002 0.027888446
4             15                      60     SA     0.019746121 0.014403292
4             15                      60     SA     0.018691589 0.015538291
4             15                      60     VLA    0.021538462 0.01686747
4             15                      60     HLA    0.017052375 0.017326733
16            5                       80     SA     0.019021739 0.015021459
16            5                       80     SA     0.020527859 0.015384615
16            5                       80     VLA    0.023217247 0.017283951
16            5                       80     HLA    0.017391304 0.016298021

and this is my plot using ggplot

enter image description here

ggplot(df)+ 
  aes(x = equivalent_iterations, y = ratio1, color = equivalent_iterations)+ 
  geom_point() + 
  facet_wrap(~axis) + 
  expand_limits(x = 0, y = 0) 

What i want is for each axis SA, VLA, HLA (i.e. each facet_wrap) a horizontal line from the first point (which is at 0 equivalent iterations) at the y intercept (which is given by the ratio1 in column 5 in the first 4 values). Any help will be greatly appreciated. Thank you in advance


Solution

  • You can treat it like any other geom_*. Just create a new column with the value of ratio1 at which you want to plot the horizontal line. I do this by sub setting the the data by those where iterations = 0 (note SA has 2 of these) and joining the ratio1 column onto the original dataframe. This column can then be passed to the aesthetics call in geom_hline().

    library(tidyverse)
    
    df %>% 
      left_join(df %>% 
                  filter(iterations == 0) %>% 
                  select(axis, intercept = ratio1)) %>% 
    
      ggplot(aes(x = equivalent_iterations, y = ratio1, 
                 color = equivalent_iterations)) +
      geom_point() + 
      geom_hline(aes(yintercept = intercept)) +
      facet_wrap(~axis) + 
      expand_limits(x = 0, y = 0) 
    

    enter image description here