如何在 R 中绘制相关矩阵之上的相关图?

How to plot, in R, a correlogram on top of a correlation matrix?

我已按照本网站 from STHDA 上的说明在 R 中绘制相关矩阵和相关图。该网站和示例非常好。但是,我想在相关矩阵的上部绘制相关图的上部。

代码如下:

library(PerformanceAnalytics)
chart.Correlation(mtcars, histogram=TRUE, pch=19)

这应该给我使用散点图的相关矩阵,以及我想要维护的直方图。但是对于情节的上半部分,我想从这段代码中获得相关图:

library(corrplot)
corrplot(cor(mtcars), type="upper", order="hclust", tl.col="black", tl.srt=45)

最明显的做法是以 pdf 格式导出所有图形,然后使用 Inkscape,但如果我可以直接从 R 中获取它会更好。有没有可能的方法吗?

谢谢。

pairs 中使用面板功能的技巧在 help(pairs) 中找到:

A panel function should not attempt to start a new plot, but just plot within a given coordinate system: thus 'plot' and 'boxplot' are not panel functions.

因此,您应该使用图形-添加 函数,例如pointslinespolygon,或者也许(可用时) ) plot(..., add=TRUE),但不是直截了当的情节。如果您实际上试图在设备虎钳上绘制它,只是从您的绘图函数返回它,那么您在评论中提出的建议(使用 SpatialPolygons)可能会产生一些效果。

在我下面的例子中,我实际上做了 "create a new plot",但我通过在已有的图上添加第二个图来作弊(基于 this SO post)。我这样做是为了缩短其他必要的 scale/shift,这仍然不是完美的,因为您似乎想要 "perfect circle",这实际上只能通过 asp=1 来保证(纵横比固定为1:1).

colorRange <- c('#69091e', '#e37f65', 'white', '#aed2e6', '#042f60')
## colorRamp() returns a function which takes as an argument a number
## on [0,1] and returns a color in the gradient in colorRange
myColorRampFunc <- colorRamp(colorRange)

panel.cor <- function(w, z, ...) {
    correlation <- cor(w, z)

    ## because the func needs [0,1] and cor gives [-1,1], we need to
    ## shift and scale it
    col <- rgb( myColorRampFunc( (1+correlation)/2 )/255 )

    ## square it to avoid visual bias due to "area vs diameter"
    radius <- sqrt(abs(correlation))
    radians <- seq(0, 2*pi, len=50)     # 50 is arbitrary
    x <- radius * cos(radians)
    y <- radius * sin(radians)
    ## make them full loops
    x <- c(x, tail(x,n=1))
    y <- c(y, tail(y,n=1))

    ## I trick the "don't create a new plot" thing by following the
    ## advice here: http://www.r-bloggers.com/multiple-y-axis-in-a-r-plot/
    ## This allows
    par(new=TRUE)
    plot(0, type='n', xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, asp=1)
    polygon(x, y, border=col, col=col)
}

pairs(mtcars, upper.panel=panel.cor)

您可以通过调整半径来操纵圆圈的大小——以不偏不倚的可视化为代价。我直接从您最初链接到的页面中获取的颜色。

类似的功能可用于下面板和对角面板。