2017-10-06 4 views
0

Salut je suis nouveau à R et ont une petite questionInsérer représentation graphique dans la parcelle de régression linéaire dans R

Je l'ensemble de données suivant composé de 12 obligations différentes:

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

Jusqu'à présent, je a obtenu les éléments suivants:

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

maintenant Je voudrais construire une obligation synthétique à 5 ans, ce qui signifie que je dois avoir les valeurs sur la ligne de régression à x = 1300 pour le jour jusqu'à l'échéance et la valeur y correspondante.

J'ai essayé de « dessiner » mon objectif dans le mot qui se présente comme suit:

syntheticbond

Les lignes en pointillés devrait être noir.

+0

S'il vous plaît, utilisez 'dput (Synthetic_bond_creation)' au lieu de 'imprimer (Synthetic_bond_creation)' – Pop

+0

Ok, j'édita – rbonac

Répondre

1

Voici un exemple (en utilisant les valeurs prédites de la régression linéaire et certains seuils que vous pouvez adapter à votre cas).

# data and model 
df <- mtcars 
model <- lm(disp ~ mpg, data = df) 
summary(model) 
# plot model 
plot(df$mpg, df$disp, xlab = "mpg", ylab = "disp") 
pred.val <- predict(model) 
lines(df$mpg, pred.val, lty = 1, col = "black") 
# set thresholds 
xmin <- 0 
ymin <- 0 
xmax <- 25 # suppose x = 25 
ymax <- as.numeric(predict(model, data.frame(mpg = xmax))) # use x to get f(x) 
# add segments 
segments(x0 = xmax, y0 = ymin, x1 = xmax, y1 = ymax, 
     lty = 2, col = "black") # vertical segment 
segments(x0 = xmin, y0 = ymax, x1 = xmax, y1 = ymax, 
     lty = 2, col = "black") # horizontal segment 

enter image description here

# using ggplot 
library(ggplot2) 
ggplot(mtcars, aes(x = mpg, y = disp))+ 
     geom_point() + 
     geom_line(aes(y = fitted(model))) + 
     geom_segment(aes(x = xmax, # vertical segment 
         xend = xmax, 
         yend = ymax), 
        y = 0, 
        linetype = "dashed") + 
     geom_segment(aes(y = ymax, # horizontal segment 
         xend = xmax, 
         yend = ymax), 
        x = 0, 
        linetype = "dashed") 

enter image description here