Hacking the plot data.frame method in R to include histograms on the diagonals and lowess fits in the scatterplots

末鹿安然 提交于 2019-12-08 07:39:22

问题


Dummy example:

N=1000
x1 = rgamma(N,5,10)
x2 = rnorm(N)+x1
x3 = (x1+x2)/(runif(N)+1)
d = data.frame(x1,x2,x3)
plot(d,col=rgb(1,0,0,.5),pch=19,cex=.5)

I'd like to take the plot data frame method and augment it to include histograms on the diagonals and lowess fits on each of the scatterplots. Is it possible to do without completely re-writing the function? Where do I even find the source code for methods?


回答1:


When you plot data.frames like this, you are basically calling the pairs() function. See ?pairs for more information. There is an example if a histogram there. Here's an example that also plots a loess line

panel.hist <- function(x, ...)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(usr[1:2], 0, 1.5) )
    h <- hist(x, plot = FALSE)
    breaks <- h$breaks; nB <- length(breaks)
    y <- h$counts; y <- y/max(y)
    rect(breaks[-nB], 0, breaks[-1], y, ...)
}
panel.loess<-function(x, y, ...) {
    ll <- loess(y~x)
    points(x,y, ...)
    nx<-seq(min(x), max(x), length.out=100)
    lines(nx, predict(ll, nx), col="black")

}


pairs(d,col=rgb(1,0,0,.5),pch=19,cex=.5, 
   diag.panel=panel.hist, 
   lower.panel=panel.loess)

which gives



来源:https://stackoverflow.com/questions/29733618/hacking-the-plot-data-frame-method-in-r-to-include-histograms-on-the-diagonals-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!