Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

graph - R code for plotting multiple line segments with unique R ranges

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...