Ensure Ordinal Variables are Factors: Make sure your ordinal variables are correctly formatted as factors, preferably ordered factors in R. ggpairs often uses the variable type to decide the plot.
# Example: Assuming 'my_data' has columns 'cont1', 'cont2', 'ord1', 'ord2'
my_data$ord1 <- ordered(my_data$ord1, levels = c("Low", "Medium", "High"))
my_data$ord2 <- ordered(my_data$ord2, levels = c("Disagree", "Neutral", "Agree"))
Custom Correlation Functions: You can create functions to calculate Spearman correlation and format the output.
library(GGally)
library(ggplot2)
library(dplyr) # For %>% and mutate
# Function to display Spearman correlation (upper triangle)
upper_fn <- function(data, mapping, ...) {
x <- .data[[mapping$x]]
y <- .data[[mapping$y]]
# Check if at least one variable is ordinal/factor-like or if both are numeric
# Use Spearman if either is ordinal/factor, or if both are numeric and you prefer Spearman
if (is.ordered(x) || is.factor(x) || is.ordered(y) || is.factor(y)) {
method <- "spearman"
} else {
method <- "pearson" # Or default to "spearman" for all if preferred
}
correlation <- cor(x, y, method = method, use = "pairwise.complete.obs")
# Add significance stars (optional)
# p_val <- cor.test(x, y, method = method, use = "pairwise.complete.obs")$p.value
# stars <- ifelse(p_val < 0.001, "***", ifelse(p_val < 0.01, "**", ifelse(p_val < 0.05, "*", "")))
ggplot(mapping = mapping) +
annotate("text", x = 0.5, y = 0.5, label = paste(round(correlation, 2)), ...) +
theme_void() +
theme(panel.background = element_rect(fill = "grey95", color = NA)) # Match background
}
# Function to display count (lower triangle for ordinal-ordinal pairs)
# You might need different functions depending on the specific pair types
lower_fn <- function(data, mapping, ...) {
x <- .data[[mapping$x]]
y <- .data[[mapping$y]]
# Specific plot for ordinal vs ordinal (e.g., counts)
if (is.ordered(x) || is.factor(x) || is.ordered(y) || is.factor(y)) {
# Option 1: Simple count plot (can get messy)
# ggplot(mapping = mapping) + geom_bin2d() + theme_void()
# Option 2: Calculate Spearman and show it (similar to upper_fn)
method <- "spearman"
correlation <- cor(as.numeric(x), as.numeric(y), method = method, use = "pairwise.complete.obs")
ggplot(mapping = mapping) +
annotate("text", x = 0.5, y = 0.5, label = paste(round(correlation, 2)), ...) +
theme_void() +
theme(panel.background = element_rect(fill = "grey95", color = NA))
} else {
# Default scatter plot for continuous-continuous
ggplot(mapping = mapping) +
geom_point(alpha = 0.5, color="blue") + # Customize point appearance
geom_smooth(method='lm', se=FALSE, color='red', size=0.5) + # Optional regression line
theme_void() +
theme(panel.background = element_rect(fill = "grey95", color = NA))
}
}
# Function for the diagonal (e.g., show variable name or density)
diag_fn <- function(data, mapping, ...) {
ggplot(data, mapping) +
geom_density(fill="lightblue", alpha=0.5) + # Density plot for continuous
# or use geom_text if you just want names or summary stats
# annotate("text", x = 0.5, y = 0.5, label = mapping$x) +
theme_void() +
theme(panel.background = element_rect(fill = "grey95", color = NA))
}
# Create the ggpairs plot
ggpairs(
my_data,
upper = list(continuous = upper_fn, combo = upper_fn, discrete = upper_fn),
lower = list(continuous = lower_fn, combo = lower_fn, discrete = lower_fn),
diag = list(continuous = diag_fn, discrete = diag_fn) # Handle diagonals separately if needed
) +
ggtitle("GGally Plot with Mixed Data Types (Spearman Focus)")