How to reverse legend key order in ggplot2

Make a fortune with your little hand, give it a thumbs up!

In this tutorial [1] , we will learn how to reverse the order of legend keys in ggplot2.

In ggplot2, when we use the color or fill arguments in aes() to color a variable, we get a legend with keys showing which keys match which colors. Here we show how to use the guides() parameter to reverse the order of the legend keys for two types of plots, a scatter plot with a legend made by the 'color' parameter, and a color Added "fill" parameter to the bar chart.

alt

Let's start by loading the tidyverse.

library(tidyverse)
theme_set(theme_bw(16))

We will use the diamond data provided by tidyverse.

diamonds %>% head()
alt

Scatter plot with colored points

Let's draw a scatterplot between two variables and color the third (categorical) variable using the color argument in aes().

Here we use the slice_sample() function to make a scatterplot using 200 data points randomly drawn from the diamond data.

diamonds %>% 
  slice_sample(200) %>%
  ggplot(aes(x=carat, y=price, color=cut))+
  geom_point()
ggsave("how_to_reverse_legend_key_order_legend_with_color.png")

This is what a scatterplot sorted with the default legend key looks like.

alt

We can reverse the legend key order using the guides() function with a color argument. We use the color parameter to invert since we created the legend with the color parameter in the aes() function earlier. The guide_legend() function with reverse = TRUE actually reverses the order of the kegend keys.

diamonds %>% 
  slice_sample(n=200) %>%
  ggplot(aes(x=carat, y=price, color=cut))+
  geom_point()+
  guides(color = guide_legend(reverse = TRUE))
ggsave("reverse_legend_key_order_legend_with_color.png")

alt

bar chart with fill color

In the second example, let's make a bar chart filled with the color specified by the second variable. We are adding color here using the fill parameter in aes() to fill the bar chart with color.

diamonds %>% 
  ggplot(aes(cut, fill=clarity))+
  geom_bar()+
  scale_fill_brewer(palette="Dark2")
ggsave("how_to_reverse_legend_key_order_legend_with_fill.png")
alt

We could use the guides() function, but this time use the fill parameter to reverse the order of the legend keys here, since the legend was created using the fill parameter in aes().

diamonds %>% 
  ggplot(aes(cut, fill=clarity))+
  geom_bar()+
  scale_fill_brewer(palette="Dark2")+
  guides(fill = guide_legend(reverse = TRUE))
ggsave("reverse_legend_key_order_for_legend_with_fill.png")
alt

Reference

[1]

Source: https://datavizpyr.com/reverse-legend-key-order-in-ggplot2/

This article is published by mdnice multi-platform

Guess you like

Origin blog.csdn.net/swindler_ice/article/details/130756893