Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Can ggplot2 find the intersections - or is there any other neat way?

In an experiment, blood pressure is measured at several time points. Blood pressure rises and declines during the experiment. I need to plot the blood pressure reaction (the easy part) and find the time points (x values) where blood pressure has doubled (the tricky part). I was wondering whether this information could be retrieved in the ggplot?

Here is an example:

# Generate data
time <- c(10, 60, 90, 200, 260, 300, 700)
value <- c(1, 6, 8, 40, 50, 60, 70)
df <- data.frame(time, value)

# The first value of "value" is the first observation.
# When the first "value" increased ten times, it is equal to 10
# Question is at what time point did the value increase ten times according to the graph?

ggplot(data=c, aes(x=time, y=value,)) + 
     geom_line() +
     geom_hline(y=10, colour="red") +
     annotate("text", hjust=0, x=170, y=15, label="I need to find the x value at the intersection")

enter image description here

Any solutions?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

No, this can't be done with ggplot2. However, it's easy to do:

v0 <- 10

f1 <- approxfun(df$time, df$value)

#we use numeric optimization here, but an analytical solution is of course possible (though a bit more work)
#this finds only one intersection, more work is required if there are more than one
optimize(function(t0) abs(f1(t0) - v0), interval = range(df$time))
#$minimum
#[1] 96.87501
#
#$objective
#[1] 3.080161e-06

If your data is bijective it gets even simpler:

f2 <- approxfun(df$value, df$time)
f2(v0)
#[1] 96.875

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...