0
votes

I know there are many many questions on here around plotting multiple lines in a graph in R, but I've been struggling with a more specific task. I would like to add multiple line segments to a graph using only the intercept and slope specified for each line. abline() would work great for this, except each line has a specific range on the X axis, and I do not want the line plotted beyond the range.

I managed to get the graph I want using plotrix, but I am hoping to publish the work, and the graph does not look up-to-par (very basic). I am somewhat familiar with ggpplot, and think that graphs generated in ggplot look much better than what I have made, especially with the various themes availible, but I cannot figure out how to do something similar using ggplot.

Code:

library(plotrix)

plot(1, type="n", xlab="PM2.5(ug/m3)", ylab="LogRR Preeclampsia ", xlim=c(0, 20), ylim=c(-1, 2.5))

ablineclip(a = 0, b = 0.3, x1=1.2, x2=3)

ablineclip(a = 0, b = 0.08, x1=8.0, x2=13.1)

ablineclip(a = 0, b = 0.5, x1=10.1, x2=18.9)

ablineclip(a = 0, b = 0.12, x1=2.6, x2=14.1)

Any help would be appreciated!

Thank you.

1

1 Answers

0
votes

You can write a basic function doing a bit of algebra to calculate the start/stop points for the line segments and then feed that into ggplot. For example

to_points <- function(intercept, slope, start, stop) {
  data.frame(
    segment = seq_along(start),
    xstart = start,
    xend = stop,
    ystart = intercept + slope*start,
    yend = intercept + slope*stop)
}

And then use that with

library(ggplot2)
segments <- to_points(0, c(0.3, 0.08, 0.5, .12),
          c(1.2, 8.0, 10.1, 2.6),
          c(3, 13.1, 18.9, 14.2))
ggplot(segments) + 
  aes(xstart, ystart, xend=xend, yend=yend) + 
  geom_segment() + 
  coord_cartesian(xlim=c(0,20), ylim=c(-1, 2.5)) + 
labs(x="PM2.5(ug/m3)", y="LogRR Preeclampsia ")

That will produce the following plot enter image description here

(Note the third segment is outside the region you specified. You can drop the coord_cartesian to see all the segments.)