2

In ggplot, It's easy to draw lines:

library(ggplot2)
library(ggpp)

ggplot() + 
  geom_abline(aes(intercept = 0, slope = 2)) +
  geom_abline(aes(intercept = 0, slope = 5)) + 
  geom_quadrant_lines()

enter image description here

But what if I want to draw rays, i.e. lines which extend to infinity only from one side?

I want my rays to start at the origin and extend into the 3rd quadrant.

One could use geom_segment to do something like this, but the problem is that I don't know the xend and yend parameters since the ray doesn't really end.

So how could I achieve this?

J. Doe
  • 1,544
  • 1
  • 11
  • 26

2 Answers2

2

you could roll your own geom_ray:

geom_ray <- function(x = 0, y = 0, rho = 0, raylength = 1, ...){
  geom_segment(aes(x = x, y = y,
                   xend = raylength * cos(rho),
                   yend = raylength * sin(rho)
                   ),
               ...
               )
}
data.frame(a = 1, b = 1) |>
  ggplot() +
  geom_ray(rho = 0, col = 'blue') +
  geom_ray(rho = pi/4, col = 'red') +
  geom_ray(rho = pi/2, col = 'green') 

geom_ray

Note that you still have to manually adjust the raylengths. (Couldn't figure out how query the axes ranges for a ggplot object not yet built.)

I_O
  • 4,983
  • 2
  • 2
  • 15
  • nice. the axis range in a continuous coordinate system are the limits +/- 5% of the range, see `?scale_x_continuous` – tjebo Apr 30 '23 at 21:37
  • Thank you tjebo. What I'd like `geom_ray` to do, though, is to pick up the calculated axis ranges *during creation* of the object, i.e. while adding the layer (ideally not even from separately examining the incoming data). – I_O May 01 '23 at 06:49
  • This is not how ggplot works out the range though. It’s based on the data. I don’t see a big problem in calculating it beforehand – tjebo May 01 '23 at 20:50
1

Would it work to just make really long lines and pick whatever viewing window you want?

ggplot() + 
  geom_segment(aes(x = 0, y = 0, xend = xe, yend = ye),
               data = data.frame(xe = -1E9, ye = -c(2, 5)*1E9)) +
  geom_quadrant_lines() +
  coord_equal(xlim = 0.05*c(-1,1), ylim = 0.05*c(-1,1))

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53