taiyun / corrplot

A visual exploratory tool on correlation matrix
https://github.com/taiyun/corrplot
Other
316 stars 86 forks source link

Return plot instead of matrix #108

Closed DominiqueMakowski closed 7 years ago

DominiqueMakowski commented 7 years ago

For my current project, I would need to store the plot in an object (named p for example) and actually plot it later on in the script (using for example plot(p)).

However, this is not possible currently as corrplot() automatically plots the figure (and cannot be delayed) and returns a correlation matrix instead of the plotted figure.

Is there a way to modify that behaviour?

Thanks

vsimko commented 7 years ago

Hi, what about simple closure like the following example:


M <- cor(mtcars) # your data here

reuseMe <- function() {
  corrplot(M, method = "square") # here comes your complicated corrplot setup
}

reuseMe()
...
reuseMe()
DominiqueMakowski commented 7 years ago

It's a good idea, unfortunately, it doesn't work in my specific case, which I'll explain a bit more.

I'd like to create a function A, within which I create the corrplot, and then store it in a list returned by the function A.

Then, I'd like to actually display the corplot bycalling the plot object from the list.

Here's what I tried:

A <- function(){
text <- "whatever else"

plot <- function() {
    p <- corrplot::corrplot.mixed(r, lower="ellipse", upper="number", order = "hclust", p.mat = p, sig.level = 0.05, insig="n", tl.pos="lt")
    return(p())
  }
return(list(text=text, plot=plot))
}

I'd like then to be able to do this to display the plot:

output <- A()
output$plot  # And, by calling this object, display the plot

However, this returns the function code 😞

function() {
    p <- corrplot::corrplot.mixed(r, lower="ellipse", upper="number", order = "hclust", p.mat = p, sig.level = 0.05, insig="n", tl.pos="lt")
    return(p())
  }
<environment: 0x000000001b0505f0>

Do you have any advices? Thanks for your help!

vsimko commented 7 years ago

no problem, functional programming is our friend:

library(corrplot)

# this function generates a list which contains a closure stored inside the "plot" element
prepareMyList <- function(r, p, text) {
  plot <- function() {
    # Note: variables "r" and "p" are bound from within the closure
    corrplot.mixed(r, lower = "ellipse", upper = "number",
                   order = "hclust", p.mat = p, sig.level = 0.05,
                   insig = "n", tl.pos = "lt")
  }
  list(text = text, plot = plot, p = p) # this is returned
}

A <- prepareMyList(cor(mtcars), .01, "whatever text")
> print(A$text) # this shows the text value copied from the "text" parameter
[1] "whatever text"
> print(A$p) # this shows the variable "p" bound by the closure
[1] 0.01
A$plot() # this plots the plot bound by the closure

image

DominiqueMakowski commented 7 years ago

Your help was more than useful. Closing this 😉