Remove your plot legend and colorize your title instead

Author
Affiliation

P K Parida

CRFM and ICAR

Published

September 6, 2024

1 Remove your plot legend and colorize your title instead

We will take the Penguins data set to plot without legend and instead colour our subplot tiltle.

Librarays required tidyverse, palmerpenguins and thematic.

Source: Mr. Albert Rapp youtube content

2 Call the libraries

library(tidyverse)
Warning: package 'ggplot2' was built under R version 4.3.3
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(thematic)
Warning: package 'thematic' was built under R version 4.3.3
library(palmerpenguins)
Warning: package 'palmerpenguins' was built under R version 4.3.3

2.1 Let us remove the NA from the data on different sex in the data

penguins <- palmerpenguins::penguins %>% 
  filter(!is.na(sex)) 

2.2 Now, it is time to provide colour to our species

colors <- thematic::okabe_ito(3)

names(colors) <- unique(penguins$species)

2.3 Providing colour in our subplot title creating variable called subplot

subtitle <- glue::glue(
  'penguins weight (in g) for the Species ',
  '<span style="color:{colors["Adelie"]}">**Adelie**</span>, ',
  '<span style="color:{colors["Chinstrap"]}">**Chinstrap**</span> ',
  'and ',
  '<span style="color:{colors["Gentoo"]}">**Gentoo**</span>'
)

2.4 Now plot the graph and remove the legend by the following code

penguins %>% 
  ggplot(aes(x=bill_length_mm, y=body_mass_g, fill =species)) +
  geom_point(shape=21, size=5, alpha=0.85, color="grey10")+
  theme_minimal(base_size = 16, base_family = 'Source Sans Pro')+
  scale_fill_manual(values=colors)+
  labs(
    x="Bill length (in mm)",
    y=element_blank(),
    title="Penguins from palmer Archipelago",
    subtitle=subtitle
  ) +
  theme(
    plot.title.position = "plot",
    text = element_text(colour="grey20"),
    axis.text=element_text(colour="grey30"),
    plot.title = element_text(
      family="Merriweather", size=26, margin = margin(b=7, unit = "mm")
    ),
    plot.subtitle = ggtext::element_markdown(size=18, lineheight =1.3),
    panel.background = element_rect(colour="grey90"),
    panel.grid.major = element_line(colour="grey90"),
    panel.grid.minor = element_blank(),
    legend.position = "none"
    )

We are using markdown to make the name as bold in the subtitle, species name, removed the minor grid, faint grey colour to major grid.