我编写了一个绘制相关热图的函数,但我无法将该图另存为对象。
library(corrplot)
library(psych)
myfun = function(ff){
corrplot(ff$r,
p.mat = round(as.matrix(ff$p),3),
method = 'circle',
type = 'lower',
sig.level = c(.001, .01, .05),
tl.pos="lt",
tl.col="black", tl.cex=1.3,
tl.offset=0.2,
cl.pos="r",
insig = "label_sig",
pch.cex = 1.3,
pch.col="red",
cl.cex = 1.3)
corrplot(ff$r, type="upper", method="number",
col="coral4", tl.pos="n", cl.pos="n", number.cex = 1.2, add=T,diag=F)
}
它确实绘制了相关热图。
ff = corr.test(mtcars, method = 'spearman')
myfun(ff)
myfun(ff)
的属性是一个matrix
而不是plot
。
p = myfun(ff)
class(p)
> class(p)
[1] "matrix"
此外,当我在控制台中键入 p
时,我无法在 Plots 窗口中看到绘图。它只是给了我一个相关矩阵。
> p
mpg cyl disp hp drat wt qsec
mpg 1.0000000 -0.9108013 -0.9088824 -0.8946646 0.65145546 -0.8864220 0.46693575
cyl -0.9108013 1.0000000 0.9276516 0.9017909 -0.67888119 0.8577282 -0.57235095
disp -0.9088824 0.9276516 1.0000000 0.8510426 -0.68359210 0.8977064 -0.45978176
hp -0.8946646 0.9017909 0.8510426 1.0000000 -0.52012499 0.7746767 -0.66660602
drat 0.6514555 -0.6788812 -0.6835921 -0.5201250 1.00000000 -0.7503904 0.09186863
wt -0.8864220 0.8577282 0.8977064 0.7746767 -0.75039041 1.0000000 -0.22540120
如何将 myfun()
创建的绘图保存为一个对象(例如 p
),以便我可以使用该对象做一些其他事情?
我们将不胜感激任何帮助。
最佳答案
corrplot()
的文档说明如下:
Value
(Invisibly) returns a reordered correlation matrix.
因此,您希望从函数中得到的是 corrplot()
(绘图)的副作用,而不是矩阵。
一种方法是使用 recordPlot()
来“保存”最新的绘图:
library(corrplot)
#> corrplot 0.84 loaded
library(psych)
myfun <- function(ff){
corrplot(ff$r,
p.mat = round(as.matrix(ff$p),3),
method = 'circle',
type = 'lower',
sig.level = c(.001, .01, .05),
tl.pos="lt",
tl.col="black", tl.cex=1.3,
tl.offset=0.2,
cl.pos="r",
insig = "label_sig",
pch.cex = 1.3,
pch.col="red",
cl.cex = 1.3)
corrplot(ff$r, type="upper", method="number",
col="coral4", tl.pos="n", cl.pos="n", number.cex = 1.2, add=T,diag=F)
recordPlot() # record the latest plot
}
ff <- corr.test(mtcars, method = 'spearman')
myfun(ff) # shows the plot
p <- myfun(ff) # still shows the plot but also saves it
p # show the recorded plot
class(p)
#> [1] "recordedplot"
由 reprex package 创建于 2020-11-27 (v0.3.0)
关于r - 如何在 r 中保存由 corrplot 函数创建的图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65031113/