rbonac
rbonac

Reputation: 125

Insert lines at specific x- and y-values in linear regression plot in R

Hey there I'm new to R and have a question

I have the following dataset consisting of 12 different bonds:

dput(Synthetic_bond_creation)
structure(list(`Days to maturity` = c(1419, 202, 1565, 1182, 
2080, 1036, 811, 2436, 1296, 609, 1792, 986), `Yield to maturity` = c(2.699, 
0.487, 4.019, 1.421, 2.394, 1.366, 1.107, 2.717, 1.592, 0.988, 
2.151, 2.278)), .Names = c("Days to maturity", "Yield to maturity"
), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-12L))

So far I got the following:

library(readxl)
Synthetic_bond_creation <- read_excel("~/UZH/Bachelorarbeit/Synthetic bond 
creation.xlsx")
View(Synthetic_bond_creation)
plot(Synthetic_bond_creation$`Days to maturity`, 
Synthetic_bond_creation$`Yield to maturity`, xlab = "Days to maturity", ylab 
= "Yield to maturity in %", main = "Bonds of 'Societe Generale SA' on 
13.03.2013")
abline(lm (Synthetic_bond_creation$`Yield to maturity` ~ 
Synthetic_bond_creation$`Days to maturity`))

rplotsynthetic

Now I would like to construct a synthetic 5-year bond, which means I need to have the values on the regression line at x=1300 for the days to maturity and the respective yield to maturity y-value which is 1.951930573 rounded to 1.95.

I tried it using:

abline(v=1300) +
abline(h=1.95)

However I would like to adjust the lines so that they end at the regression line and don't pass it. Furthermore it would be nice if the x- and y- values at the regression line intercept would appear at the respective axis

I tried to "draw" my goal in word which looks as follows:

syntheticbond

Upvotes: 0

Views: 1769

Answers (1)

shea
shea

Reputation: 528

You can add line segments after the plot and abline.

segments(x0=1300,y0=0,y1=1.95) #vertical line
segments(x0=0, y0=1.95, x1=1300) #horizontal line

The default is x,y for the starting (x0, y0) and end point(x1, y1), but since these are horizontal and vertical, you only change either an x or y, respectively. You can change the line types and colors as usual, i.e. lty or col.

You might have to tweak the values for the ends, but you get the idea.

Upvotes: 2

Related Questions