How to Change GGPlot Legend Order



How to Change GGPlot Legend Order

In this article, you will learn how to change a ggplot legend order.

Related Book

GGPlot2 Essentials for Great Data Visualization in R

Prerequisites

Load the ggplot2 package and set the theme function theme_classic() as the default theme:

library(ggplot2)
theme_set(
  theme_classic() 
  )

Basic plots

p <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot(aes(color = Species)) +
  scale_color_manual(values = c("#E7B800", "#2E9FDF", "#FC4E07"))
p

Reorder legend labels

Changing the order of legend labels can be achieved by reordering the factor levels of the Species variable mapped to the color aesthetic.

  1. Reorder the factor levels:
# Default order
levels(iris$Species)
## [1] "setosa"     "versicolor" "virginica"
# Reverse the order as follow
iris$Species <- factor(iris$Species, levels = rev(levels(iris$Species)))
# Or specify the factor levels in the order you want
iris$Species <- factor(iris$Species, levels = c("virginica", "versicolor", "setosa"))
  1. Create the plot:
ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  geom_boxplot(aes(color = Species)) +
  scale_color_manual(values = c("#E7B800", "#2E9FDF", "#FC4E07"))

Version: Français





Comment ( 1 )

  • Haley

    Hi,
    how do I change the order not in the legend but in the graph itself? I’ve created a scatter plot but the factor that gives the colour is mixed up. I’d like to have high-medium-low but it is in high-low-medium.
    Any ideas?
    Thanks in advance

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments