Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change order of legend in ggplot2

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading