rggplot2calendarlegendlevels

Reorder legend levels in CalendR


Using CalendR to plot fishing days for boats. How do you go about reordering legend levels e.g. boat names first then public holidays last?

Load packages, create events & plot calander:

## load packages
library(tidyverse)
library(calendR)
library(viridis) 
library(scales)

## events
events <- rep(NA, 366) ## 2024 is a leap year

## corresponding events
events[c(3, 22, 45, 63, 100, 140, 195, 234, 300)] <- "Big Catch" ## boat 1
events[c(36, 59, 78, 123, 167, 210, 289, 340)] <- "Fish Tales" ## boat 2
events[c(25, 80, 90, 155, 255, 297, 339)] <- "Marlin" ## boat 3
events[c(1, 89, 92, 142, 143, 239, 360, 361)] <- "Holiday" ## holidays

## holiday to come last
desired_order <- factor(c(levels = c("Big Catch", "Fish Tales", "Marlin", "Holiday"))) 

## select desired order and colourway
show_col(viridis_pal()(5)) ## colour palette = viridis
print(viridis_pal()(5)) ## copy values from consol

## order colours
ordered_colours <- c("#3b528bff", "#21908cff", "#5dc863ff", "lightgray")[order(desired_order)]

## plot
calendR(year = 2024, start = "M",
        special.days = events,
        special.col = c(ordered_colours), 
        lty = 1, bg.col = "white",    
        subtitle.col = 1,
        weeknames = c("M", "T", "W", "T", "F", "S", "S"),
        day.size = 3.5,
        orientation = "l",
        legend.pos = "bottom")

I'm looking for the legend to display Big Catch, then Fish Tales and then Marlin, with Holiday last. Mine switches to alphabetical order when plotting.


Solution

  • Havent't found an option to set the order for the fill colors. But one option would be to use scale_fill_manual and set the order via the limits= argument:

    library(calendR)
    library(ggplot2)
    
    ordered_colours <- setNames(ordered_colours, c("Big Catch", "Fish Tales", "Marlin", "Holiday"))
    
    calendR(
      year = 2024, start = "M",
      special.days = events,
      special.col = c(ordered_colours),
      lty = 1, bg.col = "white",
      subtitle.col = 1,
      weeknames = c("M", "T", "W", "T", "F", "S", "S"),
      day.size = 3.5,
      orientation = "l",
      legend.pos = "bottom"
    ) +
      scale_fill_manual(
        values = ordered_colours,
        limits = names(ordered_colours),
        na.value = "transparent"
      )
    #> Scale for fill is already present.
    #> Adding another scale for fill, which will replace the existing scale.