Home > front end >  Change order of legend in ggplot2
Change order of legend in ggplot2

Time:10-13

Example graph of my problem: https://imgur.com/a/Pgygzld (Code at bottom)

I would like to reorder my legend in a bar plot in ggplot2. Currently the fill is on a scale from "Inside", "Close" and "Far". This is basically the distance from a parking area of an escooter the actual scooter stands parked.

Now I want the Inside to fill the bottom (which is does), but I want "Close" and "Far" to switch places.

Anyone know how to do that?

Dummy code;

y <- c(1,1,1,1,1)
x <- c("Bolt", "Zipp", "Voi", "Bolt", "Zipp")
z <- c("Inside", "Inside", "Close", "Far", "Far")
df <- data.frame(x, y, z)

dftest %>%
  ggplot(aes(x = x,
             y = y,
             fill = z))  
  labs(x = "Operator",
       y = "Amount of vehicles",
       fill = "Proximity")  
  geom_bar(stat = "identity")  
  scale_fill_grey()  
  theme_bw()

CodePudding user response:

Discrete scales take a limits parameter, "A character vector that defines possible values of the scale and their order" . You can check ?ggplot2::scale_fill_grey & ?ggplot2::discrete_scale for reference.

Though when you have more categories you might want to use factors instead (i.e. df %>% mutate(z = factor(z,levels = c("Far", "Close", "Inside"))) before piping it into ggplot() ), factor levels set the default order in fill legend. And when dealing with factors, it's worth checking https://forcats.tidyverse.org/ .

library(ggplot2)
library(magrittr)

y <- c(1,1,1,1,1)
x <- c("Bolt", "Zipp", "Voi", "Bolt", "Zipp")
z <- c("Inside", "Inside", "Close", "Far", "Far")
df <- data.frame(x, y, z)

df %>%
  ggplot(aes(x = x,
             y = y,
             fill = z))  
  labs(x = "Operator",
       y = "Amount of vehicles",
       fill = "Proximity")  
  geom_bar(stat = "identity")  
  scale_fill_grey(limits = c("Far", "Close", "Inside"))  
  theme_bw()

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

  • Related