如何在R中添加色标?

时间:2019-04-06 06:56:43

标签: r plot correlation

我已经按照r2evans在此网站上的说明在R中绘制了相关矩阵和相关图。该网站和示例确实很棒。但是,我想为相关矩阵的上部添加一个色标。

代码如下:

colorRange <- c('#69091e','#e37f65','white','#aed2e6','#042f60')
myColorRampFunc <- colorRamp(colorRange)
panel.cor <- function(w,z,...){
    correlation <-cor(w,z)
    col <- rgb(myColorRampFunc((1+correlation)/2)/255)
    radius <- sqrt(abs(correlation))
    radians <- seq(0,2*pi,len = 50)
    x <- radius * cos(radians)
    y <- radius * sin(radians)
    x <- c(x,tail(x,n = 1))
    y <- c(y,tail(y,n = 1))
    par(new = TRUE)
    plot(2,tyoe = 'n',xlim = c(-1,1),ylim = c(-1,1),axes = FALSE,asp = 1)
    polygon(x,y,border = col,col = col)
    usr <- par("usr"); on.exit(par(usr)) 
    par(usr = c(0, 1, 0, 1)) 
    r <- cor.test(w, z)$p.value
    txt <- format(c(r, 0.123456789), digits = 2)[1] 
    text(0.5, 0.5, txt, cex = 1.5) 
}
panel.lm <- function(w,z,col=par('col'),bg = NA,pch = par('pch'),cex = 1,col.smooth = 'black',...){
    points(w,z,pch = pch,col = col,bg = bg,cex = cex)
    abline(stats::lm(z~w),col = col.smooth,...)
}
pairs(mtcars,upper.panel = panel.cor,lower.panel = panel.lm)

这是我得到的结果:

Picture1

我想添加一个色标,例如:

Picture2

谢谢!

0 个答案:

没有答案