'How can I reorder facet wrap by the values of the first column?
The following code is from Stefan, who answered a related question
library(ggplot2)
library(dplyr)
library(tidyr)
library(tidytext)
mtcars2 <- as_tibble(mtcars, rownames = 'car')
mtcars_long_numeric_with_mpg <- mtcars2 %>%
select(car, mpg, disp, hp, drat, wt, qsec) %>%
pivot_longer(names_to = 'names', values_to = 'values', 2:7) %>%
mutate(car = tidytext::reorder_within(car, values, names))
ggplot(mtcars_long_numeric_with_mpg, aes(x = values, y = reorder(car, values))) +
geom_point() +
tidytext::scale_y_reordered() +
facet_wrap(~names, scales = 'free')+
theme(text = element_text(size=6))
What I'm wondering is how to reorder each plot by the values of the first plot. So if I wanted each subsequent plot to be ordered by the values from greatest to largest (or vice versa) of the 'disp' values, rather than each ordered by its own sorted values. I know I have to fix the y-axis, which I have already done, but I can't figure out how to sort all values by just the first facet. Thanks in advance for any help!
Solution 1:[1]
you could reorder car by disp before melting the dataframe to long format:
mtcars_long <-
mtcars %>%
rownames_to_column('car') %>%
## set the levels of factor 'model' before reshaping:
mutate(model = fct_reorder(model, disp, mean)) %>%
pivot_longer(cols = -car, ## stack all columns except 'car'
names_to = 'parameter'
) ## stack all columns except model
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | I_O |

