Home > database >  Reordering by x bar using one value of facet variable
Reordering by x bar using one value of facet variable

Time:06-08

For the dataset below, I'd like to customize my below plot by ordering states according to the total number of deaths experienced by age 65. I tried the below code.

The answer enter image description here

CodePudding user response:

Popname is a factor with some levels that already sort the values. You have to rearrange them:

> CAPS_2019$PopName
[1] AK AK AK AL AL AL AR AR AR
Levels: AK AL AR

You can arrange the df by descending order in Age and Dx so the first values in Popname are sorted.

CAPS_2019 %>% arrange(desc(Age),desc(Dx))

# A tibble: 9 x 3
  Age      Dx PopName
  <fct> <dbl> <fct>  
1 65    21.9  AL     
2 65    21.3  AR     
3 65    17.2  AK     
4 50     8.86 AL     
5 50     7.89 AR     
6 50     7.85 AK     
7 30     3.06 AK     
8 30     2.85 AL     
9 30     2.52 AR 

If you extract the unique values of Popname already sorted you can use them to reset the levels as you want. But, because you are using coord_flip() to flip the axis, the levels will be sorted the other way round in your plot. You can fix it in the ggplot code or just sort the levels in ascending order:

CAPS_2019 %>% arrange(desc(Age),Dx) %>% pull(PopName) %>% unique() %>% as.character()
[1] "AK" "AR" "AL"

Then, just edit the Popname column with the new levels:

CAPS_2019$PopName = factor(as.character(CAPS_2019$PopName), # the values
                           CAPS_2019 %>% arrange(desc(Age),Dx) %>% pull(PopName) %>% unique() %>% as.character()  # the levels sorted in ascending
)
[1] AK AK AK AL AL AL AR AR AR
Levels: AK AR AL

Next, plot the graph as it is. Changing the aesthetic for x-axis in ggplot() as: x = Popname

enter image description here

PS: Note if you don't flip the axis then the plot are sorted in ascending.

enter image description here

  • Related