10.4 Reversing the Order of Items in a Legend
10.4.2 Solution
Add guides (fill = guide_legend(reverse = TRUE)
) to reverse the order of the legend, as in Figure 10.7 (for other aesthetics, replace fill
with the name of the aesthetic, such as colour
or size
):
# Create the base plot
ggplot(PlantGrowth, aes(x = group, y = weight, fill = group)) +
pg_plot <- geom_boxplot()
pg_plot
# Reverse the legend order
+
pg_plot guides(fill = guide_legend(reverse = TRUE))
![Default order for legend (left); Reversed order (right)](R-Graphics-Cookbook-2e_files/figure-html/FIG-LEGEND-TITLE-REVERSE-1.png)
![Default order for legend (left); Reversed order (right)](R-Graphics-Cookbook-2e_files/figure-html/FIG-LEGEND-TITLE-REVERSE-2.png)
Figure 10.7: Default order for legend (left); Reversed order (right)