Search code examples
rggplot2ggforce

Color legends based on custom-fill colors using ggforce::geom_mark_ellipse()


I am trying to use custom colors for my plot and legends. However, when I run the code below, the legends disappear (see Fig. 1). The legends are present when I do not use custom colors to fill the ellipses (see Fig. 2). I will appreciate any suggestions.

Fig. 1:

enter image description here

Fig. 2:

enter image description here

library(palmerpenguins)
library(tidyverse)
library(ggplot2)
library(ggforce)

penguins <- penguins %>%
  drop_na()
penguins %>% head() %>% print()
cols <- c("#0066cc","#9933ff","#66cc33")
my_color <- rep("", nrow(penguins))
cidx <- 0
for (color in unique(penguins$species)){
  cidx <- cidx + 1
  idx <- which(penguins$species == color)
  my_color[idx] <- cols[cidx]
}

p <- penguins %>%
  ggplot(aes(x = bill_length_mm,
             y = flipper_length_mm))+
  geom_mark_ellipse(aes(fill = I(my_color), alpha = I(0.2)),
  # geom_mark_ellipse(aes(fill = species),
                   expand = unit(0.5,"mm"),
                   size = 0) +
  geom_point(color = I(my_color))

plot(p)

Solution

  • You could achieve your requirements within the ggplot build-up using scales...

    library(palmerpenguins)
    library(ggplot2)
    library(ggforce)
    library(tidyr)
    
    penguins <- 
      penguins  |> 
      drop_na()
    
    
    cols <- c("#0066cc","#9933ff","#66cc33")
    
    penguins |> 
      ggplot(aes(x = bill_length_mm,
                 y = flipper_length_mm))+
      geom_mark_ellipse(aes(fill = species),
                        colour = NA,
                        alpha = 0.2,
                        expand = unit(0.5,"mm"),
                        size = 0) +
      geom_point(aes(color = species))+
      scale_fill_manual(breaks = unique(penguins$species),
                        values = cols)+
      scale_colour_manual(breaks = unique(penguins$species),
                        values = cols)
    

    Created on 2022-10-21 with reprex v2.0.2