简体   繁体   中英

How can I plot a tangent line in R?

在此处输入图像描述

Hi guys!

I need some help to create the picture above. I have the following Code (the blue line):

bondprc <- function(p, r, ttm, y){
  cf <- c(rep(p * r, ttm - 1), p * (1 + r))
  cf <- data.frame(cf)
  cf$t <- as.numeric(rownames(cf))
  cf$pv_factor <- 1 / (1 + y)^cf$t
  cf$pv <- cf$cf * cf$pv_factor
  sum(cf$pv)
}

prc_yld <- seq(0.02, 0.4, 0.01)

# Convert to data frame
prc_yld <- data.frame(prc_yld)

# Calculate bond price given different yields
for (i in 1:nrow(prc_yld)) {
  prc_yld$price[i] <- bondprc(100, 0.10, 20, prc_yld$prc_yld[i])  
}

# Plot P/YTM relationship
library(ggplot2)

ggplot(prc_yld, aes(x=prc_yld, y = price)) + geom_line() + labs(title ="Price/YTM Relationship",x="Yield", y= "Value")

I tried to calculate the tangent line by hand, but it does not really work.

## tangent 

Slope <- c(0,apply(prc_yld, 2, diff)[,2]) 
prc_yld <- cbind(prc_yld, Slope) 
prc_yld
## tangent: t(x) = m* x + n 
## Assume x = 0.1 --> y= 100, m = -9.12854
n <-  100 + 9.12854 * 0.1 
tangent <- function(x){
  -9.12854 * x +n 
}

ggplot(data.frame(x =c(0,0.4)), aes(x=x)) + stat_function(fun = tangent)

I also have no idea how to color the area between the curves. Thanks for any help!

The key here is first to calculate the slope and the intercept correctly, and then use geom_ribbon and geom_abline . So if you wish to calculate the slope in 0.1, I suggest you calculate the ratio between the y increment and x increment in the interval x = 0.9 and x = 0.11, that is:

xincrement <- 0.02
yincrement <- prc_yld[10, 2] - prc_yld[8, 2]
slope <- yincrement/xincrement

Then, the intercept is:

intercept <- 100-slope*0.1

With these values, we can calculate the y values of the tangent line:

yvalues <- slope*prc_yld$prc_yld + intercept

Now, let's combine all together:

 prc_yld <- as.data.frame(cbind(prc_yld, yvalues))

Now, the plot:

ggplot(prc_yld, aes(x=prc_yld, y = price)) + 
    geom_ribbon(data = prc_yld, aes(x = prc_yld, ymax = price, ymin = yvalues), fill = "green") +
      geom_line(color = "red", size = 1) + 
      labs(title ="Price/YTM Relationship",x="Yield", y= "Value") + 
      geom_abline(slope = slope, intercept = intercept, color = "blue", size = 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM