繁体   English   中英

在R中组合3个不同的矩阵图

[英]Combining 3 different matrix plots in R

谁能告诉我如何创建以3种不同矩阵数据集为特征的图。 总的来说,我有3个不同的数据矩阵,均为1 * 1001维,我希望在同一张图上绘制所有3个矩阵。

我设法一次绘制了一个矩阵,并汇编了代码以创建其他2个矩阵,但未进行绘制。 B [i,]是随机生成的数据。 我想知道的是将所有3个图汇总到一张图上的编码。

一个矩阵的代码:ntime <-1000平均价格每个时间步长<-matrix(0,nrow = 1,ncol = ntime + 1)

for(i in 1:(ntime+1)){
average.price.at.each.timestep[i]<-mean(B[i,])
}

matplot(t, t(average.price.at.each.timestep), type="l", lty=1, main="MC Price of a Zero Coupon Bond", ylab="Price", xlab = "Option Exercise Date") 

代码3:

average.price.at.each.timestep<-matrix(0,nrow=1,ncol=ntime+1)
s.e.at.each.time <-matrix(0,nrow=1,ncol=ntime+1)
upper.c.l.at <- matrix(0,nrow=1,ncol=ntime+1)
lower.c.l.at <- matrix(0,nrow=1,ncol=ntime+1)
std <- function(x) sd(x)/sqrt(length(x))

for(i in 1:(ntime+1)){
average.price.at.each.timestep[i]<-mean(B[i,])
s.e.at.each.time[i] <- std(B[i,])
upper.c.l.at[i] <- average.price.at.each.timestep[i]+1.96*s.e.at.each.time[i]
lower.c.l.at[i] <- average.price.at.each.timestep[i]-1.96*s.e.at.each.time[i]
}

我仍在为此苦苦挣扎,因为我无法获得与数据集相匹配的解决方案,我现在将下面的代码生成了一个生成矩阵B的工作示例,以便您可以查看正在处理的数据。 如您所见,它会绘制出不同价格的图,我想要一个具有平均价格和平均值的置信区间的图。

# Define Bond Price Parameters
#
P<-1                            #par value

# Define Vasicek Model Parameters
#
rev.rate<-0.3                   #speed of reversion
long.term.mean<-0.1             #long term level of the mean
sigma<-0.05                  #volatility
r0<-0.03                            #spot interest rate
Strike<-0.05
# Define Simulation Parameters
#
T<-50                           #time to expiry
ntime<-1000                 #number of timesteps
yearstep<-ntime/T               #yearstep
npaths<-1000                    #number of paths
dt<-T/ntime                     #timestep
R <- matrix(0,nrow=ntime+1,ncol=npaths) #matrix of Vasicek interest rate values
B <- matrix(0,nrow=ntime+1,ncol=npaths) # matrix of Bond Prices 

R[1,]<-r0                   #specifies that all paths start at specified spot rate
B[1,]<-P

# do loop which generates values to fill matrix R with multiple paths of Interest Rates as they evolve over time.
# stochastic process based on standard normal distribution

for (j in 1:npaths) {
 for (i in 1:ntime) {
   dZ <-rnorm(1,mean=0,sd=1)*sqrt(dt)
   Rij<-R[i,j]
   Bij<-B[i,j]
   dr <-rev.rate*(long.term.mean-Rij)*dt+sigma*dZ
   R[i+1,j]<-Rij+dr
   B[i+1,j]<-Bij*exp(-R[i+1,j]*dt)   
  }
} 

t<-seq(0,T,dt)
par(mfcol = c(3,3))


matplot(t, B[,1:pmin(20,npaths)], type="l", lty=1, main="Price of a Zero Coupon Bond", ylab="Price", xlab = "Time to Expiry") 

您的示例不可复制,因此我创建了一些假数据,希望它们的结构与您的类似。 如果这不是您想要的,请告诉我,我会根据需要进行更新。

# Fake data
ntime <- 100 
mat1 <- matrix(rnorm(ntime+1, 10, 2), nrow=1, ncol=ntime+1)
mat2 <- matrix(rnorm(ntime+1, 20, 2), nrow=1, ncol=ntime+1)
mat3 <- matrix(rnorm(ntime+1, 30, 2), nrow=1, ncol=ntime+1)

matplot(1:(ntime+1), t(mat1), type="l", lty=1, ylim=c(0, max(c(mat1,mat2,mat3))),
        main="MC Price of a Zero Coupon Bond", 
        ylab="Price", xlab = "Option Exercise Date") 

# Add lines for mat2 and mat3
lines(1:101, mat2, col="red")
lines(1:101, mat3, col="blue")

在此处输入图片说明

更新:这是您要做什么?

matplot(t, t(average.price.at.each.timestep), type="l", lty=1, 
        main="MC Price of a Zero Coupon Bond", ylab="Price", 
        xlab = "Option Exercise Date") 
matlines(t, t(upper.c.l.at), lty=2, col="red")
matlines(t, t(lower.c.l.at), lty=2, col="green")

请参见下图。 如果您要绘制多个列(如在更新的示例中绘制了20条单独的路径),并且要为所有列添加上下CI(尽管这会使绘图不可读),则只需使用矩阵即可那对应于每个路径上,下CI值average.price.at.each.timestep和使用matlines将它们添加到您现有的多路径的情节。

在此处输入图片说明

使用ggplot2reshape2可以ggplot2这一点。 您拥有的结构有些尴尬,您可以通过使用数据框而不是矩阵来进行改进。

#Dummy data
average.price.at.each.timestep <- rnorm(1000, sd=0.01)
s.e.at.each.time <- rnorm(1000, sd=0.0005, mean=1)

#CIs (note you can vectorise this):
upper.c.l.at <- average.price.at.each.timestep+1.96*s.e.at.each.time
lower.c.l.at <- average.price.at.each.timestep-1.96*s.e.at.each.time

#create a data frame:
prices <- data.frame(time = 1:length(average.price.at.each.timestep), price=average.price.at.each.timestep, upperCI= upper.c.l.at, lowerCI= lower.c.l.at)

library(reshape2)
#turn the data frame into time, variable, value triplets
prices.t <- melt(prices, id.vars=c("time"))

#plot
library(ggplot2)
ggplot(prices.t, aes(time, value, colour=variable)) + geom_line()

这将产生以下图: 在此处输入图片说明

通过使用geom_ribbon可以对此进行一些改进:

ggplot(prices, aes(time, price)) + geom_ribbon(aes(ymin=lowerCI, ymax=upperCI), alpha=0.1) + geom_line()

产生此图:

在此处输入图片说明

这是另一个略有不同的ggplot解决方案,它不需要您先计算置信度限制-ggplot会为您完成。

# create sample dataset
set.seed(1)   # for reproducible example
B <- matrix(rnorm(1000,mean=rep(10+1:10/2,each=10)),nc=10)

library(ggplot2)
library(reshape2)   # for melt(...)
gg <- melt(data.frame(date=1:nrow(B),B), id="date")
ggplot(gg, aes(x=date,y=value)) + 
  stat_summary(fun.y = mean, geom="line")+
  stat_summary(fun.y = function(y)mean(y)-1.96*sd(y)/sqrt(length(y)), geom="line",linetype="dotted", color="blue")+
  stat_summary(fun.y = function(y)mean(y)+1.96*sd(y)/sqrt(length(y)), geom="line",linetype="dotted", color="blue")+
  theme_bw()

stat_summary(...)总结给定x值(日期)的y值。 因此,在第一个调用中,它计算平均值,在第二个调用中,计算lowerCL,在第三个调用中,计算upperCL。

您还可以创建一个CL(...)函数,然后调用该函数:

CL <- function(x,level=0.95,type=c("lower","upper")) {
  fact <- c(lower=-1,upper=1)
  mean(x) - fact[type]*qnorm((1-level)/2)*sd(x)/sqrt(length(x))
}
ggplot(gg, aes(x=date,y=value)) + 
  stat_summary(fun.y = mean, geom="line")+
  stat_summary(fun.y = CL, type="lower", geom="line",linetype="dotted", color="blue")+
  stat_summary(fun.y = CL, type="upper", geom="line",linetype="dotted", color="blue")+
  theme_bw()

这将产生与上面相同的图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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