Search code examples
rggplot2renamefacet-grid

How to rename figure legend in ggplot? aes gives length error


I'm new to using R and I've run into a problem.

I've made a scatterplot using geom_point.

scatterplot

I've managed to rename the facet grid labels, but I don't know how to rename the figure legend. I've tried renaming the line geom_point(aes(colour = Diet)) to geom_point(aes(colour = diet_names)) but the following error occurs:

Error: Aesthetics must be either length 1 or the same as the data (23): colour.

If I remove all but one of the values below (E.g. just leaving in fish_or = "Fish") the error doesn't occur, but obviously I don't want just one coloured value on the table.

    diet_names <- c(
      fish_or = "Fish" ,
      fruit_pu = "Fruit" ,
      insects_nectar_bl = "Insects & Nectar" ,
      insects_re = "Insects" ,
      seeds_gr = "Seeds")

I'd like to edit the legend into something more clear as it's data for a poster I'm making. Thanks :)

Full code:

library(ggplot2)
library(dplyr)
Birdbeaks <- read.csv("Birdbeaks.csv", stringsAsFactors = FALSE)

diet_names <- c(
fish_or = "Fish" ,
fruit_pu = "Fruit" ,
insects_nectar_bl = "Insects & Nectar" ,
insects_re = "Insects" ,
seeds_gr = "Seeds") 

ggplot(Birdbeaks, aes(bill_lengthavg, bill_depthavg)) +
geom_point(aes(colour = diet)) +
labs(x = "Bill Length(cm)", y = "Bill Depth(cm)", colour = "Diet")+ 
guides(col = guide_legend(override.aes = list(shape = 15, size = 5))) +
theme_update()+
facet_grid(~diet, scales="fixed", labeller = as_labeller(diet_names))

Solution

  • Hope this is useful

    library(magrittr)
    library(dplyr)
    library(ggplot2)
    
        Birdbeaks %>%
          mutate(diet = case_when(
            diet == "fish_or" ~ "Fish",
            diet == "fruit_pu" ~ "Fruit",
            diet == "insects_nectar_bl" ~ "Insects & Nectar",
            diet == "insects_re" ~ "Insects",
            diet == "seeds_gr" ~ "Seeds"
          )) %>%
          ggplot(aes(bill_lengthavg, bill_depthavg)) +
            geom_point(aes(colour = diet)) +
            labs(x = "Bill Length(cm)", y = "Bill Depth(cm)", colour = "Diet") +
            guides(col = guide_legend(override.aes = list(shape = 15, size = 5))) +
            theme_update() +
            facet_grid(~diet, scales = "fixed")