gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:59:00 26 4
gpt4 key购买 nike

我已按照本网站上的说明进行操作 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.

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

在下面的示例中,我实际上是在“创建一个新图”,但我作弊(基于 this SO post ),在已经存在的图之上添加了第二个图。我这样做是为了缩短其他必要的缩放/偏移,这仍然不是完美的,因为你似乎想要一个“完美的圆”,这实际上只能通过 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)

enter image description here

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

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

关于r - 如何在 R 中绘制相关矩阵之上的相关图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com