summaryrefslogtreecommitdiff
path: root/R
diff options
context:
space:
mode:
Diffstat (limited to 'R')
-rw-r--r--R/corplot.R79
-rw-r--r--R/gg_csobczak.R6
2 files changed, 83 insertions, 2 deletions
diff --git a/R/corplot.R b/R/corplot.R
new file mode 100644
index 0000000..c18e904
--- /dev/null
+++ b/R/corplot.R
@@ -0,0 +1,79 @@
+utils::globalVariables(c('i', 'j', 'value'))
+#' Correlation PLot (Upper Triangle)
+#'
+#' Minimal ggplot2 correlation plot showing the upper triangle
+#' in the top-right corner with no axis labels.
+#' @param R A square numeric correlation matrix
+#' @param title Optional plot title
+#'
+#' @return A ggplot object
+#'
+#' @examples
+#' X <- matrix(data = rnorm(100), nrow = 10)
+#' R <- cor(X)
+#' corplot(R, title = 'Example Correlation Plot')
+#'
+#' @importFrom reshape2 melt
+#' @import ggplot2
+#' @export
+corplot <- function(R, title = NULL){
+ R <- tryCatch({
+ if(is.matrix(R)){
+ if(nrow(R) == ncol(R)){
+ R[upper.tri(R)]
+ }
+ }else if(is.vector(R)){
+ m <- length(R)
+ n <- (1 + sqrt(1 + 8 * m)) / 2
+ if(n == floor(n)){
+ R
+ }else{
+ stop('Input length not compatible with upper triangle')
+ }
+ }else{
+ Rm <- as.matrix(R)
+ if(nrow(Rm) == ncol(Rm)){
+ Rm[upper.tri(Rm)]
+ }
+ }
+ }, error = function(e){
+ stop(paste('Invalid input for corplot:', e$message))
+ })
+
+ # Now get a df from the upper triangle
+ m <- length(R)
+ n <- as.integer((1 + sqrt(1 + 8 * m)) / 2)
+ M <- matrix(NA, n, n)
+ M[upper.tri(M)] <- R
+ df <- reshape2::melt(M, na.rm = TRUE)
+ colnames(df) <- c('i', 'j', 'value')
+ df$i <- factor(df$i, levels = 1:n)
+ df$j <- factor(df$j, levels = 1:n)
+
+ # And plot it
+ p <- ggplot2::ggplot(
+ data = df,
+ ggplot2::aes(x = i, y = j, fill = value)
+ ) +
+ ggplot2::geom_tile() +
+ ggplot2::scale_fill_gradient2(
+ low = 'red',
+ mid = 'white',
+ high = 'blue',
+ midpoint = 0,
+ name = expression(rho)
+ ) +
+ ggplot2::scale_x_discrete(limits = rev(levels(df$i))) +
+ ggplot2::scale_y_discrete(limits = levels(df$j)) +
+ ggplot2::coord_fixed() +
+ ggplot2::theme_void()
+
+ if(!is.null(title)){
+ p <- p +
+ ggplot2::ggtitle(title) +
+ ggplot2::theme(
+ plot.title = ggplot2::element_text(hjust = 0.5)
+ )
+ }
+ return(p)
+}
diff --git a/R/gg_csobczak.R b/R/gg_csobczak.R
index 97448a3..2817637 100644
--- a/R/gg_csobczak.R
+++ b/R/gg_csobczak.R
@@ -4,10 +4,12 @@
#' @param p A ggplot object to add formatting to.
#' @keywords ggplot plot p
#' @export
+#' @import ggplot2
#' @examples
#' df <- data.frame(x=rnorm(10), y=rnorm(10))
-#' p <- ggplot(data=df, aes(x=x, y=y)) + geom_point()
+#' p <- ggplot2::ggplot(data=df, ggplot2::aes(x = x, y = y)) + ggplot2::geom_point()
#' p <- gg_csobczak(p)
gg_csobczak <- function(p){
- p + theme_classic()
+ p <- p + ggplot2::theme_classic()
+ return(p)
}