如何找到R中两条曲线的交点的x截距?

时间:2018-11-18 12:38:15

标签: r ggplot2 plot

df1=read.csv("file1.csv")
df2=read.csv("file2.csv") 
ggplot(df1, aes(x,y))+geom_line()+geom_line(aes(df2$x, df2$y))
df2$x[abs(df2$y-df2$x)<0.001 & df2$x>5 & df2$x<7)]

我有csv数据,我将其作为数据帧导入到R环境中。然后,我使用ggplot将两个数据框覆盖在一个绘图上。我需要找到曲线的交点位于x = 5和x = 7.5之间的点。你能帮我吗? 如代码片段所示,我使用的最后一行代码没有显示任何值,但可以看到图中的交点。 the 2 plots overlaid using ggplot

1 个答案:

答案 0 :(得分:3)

您只需要找到x值(以下称为x)在指定范围内,而每个y值(分别为y1y2)的点等于。天真的方法可能是

which(x <= xmax & x >= xmin & y1 == y2)

但是,由于Why are these numbers not equal?中详细说明的原因,这种方法并非总能解决。但是,您可以执行以下操作:

# Create an dataframe:
x <- seq(0, 10, 0.01)
y1 <- sin(x)
y2 <- cos(x)
df <- data.frame(x = x, y1 = y1, y2 = y2)
# Let's plot the curves
# I like to use the colorblind-friendly palette from
# Wong, Bang. 2011. "Points of view: Color blindness." Nature Methods 8:441.
wong_palette <- c("#e69f00", "#56b4e9")
# Plot the first curve
plot(x, y1, type = "l", xlab = "V1", ylab = "V2", col = wong_palette[1])
# Add the second
lines(x, y2, col = wong_palette[2])
# What are the intersections?
equivalent <- function(x, y, tol = 0.005) abs(x - y) < tol
xmin <- 3
xmax <- 8
intersection_indices <- which(equivalent(y1, y2) & x >= xmin & x <= xmax)
x[intersection_indices]
#> [1] 3.93 7.07
points(x[intersection_indices], y1[intersection_indices])

reprex package(v0.2.1)于2018-11-18创建

请注意,我使用自己创建的示例数据来完成此操作,因为您提供的代码段不足以提供示例数据。为了将来写出更好的问题提供参考,您可能需要查看How to make a great R reproducible example