ggobi / ggally

R package that extends ggplot2
http://ggobi.github.io/ggally/
588 stars 118 forks source link

Adding legend to ggpairs #486

Open pshukla63 opened 10 months ago

pshukla63 commented 10 months ago

Hello! I have a rather complex ggpairs plot that I am trying to plot. I want the color gradient legend and fill legend to both appear but I don't know how to achieve this. This is example code:

lowerFn <- function(data, mapping) {
  ggplot(data = data, mapping = mapping) +
    geom_point(alpha = 0.6) +
    scale_color_gradient2(low = "#B2182B", midpoint = 1, high = "#2166AC")
}

upperFn <- function(data, mapping) {
  ggplot(data = data, mapping = mapping) +
    geom_point(alpha = 0.5) +
    scale_color_manual(values = my_colors)
}

my_colors <- c(A = "green", B = "purple", C = "yellow")

df <- data.frame(PC1 = rnorm(100), PC2 = rnorm(100), PC3 = rnorm(100), 
                 type = sample(c("A", "B", "C"), 100, replace = TRUE), distance = rnorm(100))

ggpairs(df %>% select(starts_with("PC")),
  upper = list(
    mapping = aes(color = df$type),
    continuous = upperFn
  ),
  lower = list(
    mapping = aes(color = df$distance),
    continuous = lowerFn
  ),
  diag = list(mapping = aes(fill = df$type)), legend = 1
) +
  theme_bw() + scale_fill_manual(values = my_colors) + labs(fill = "Type")

Thank you!