Question: Is it possible to order line plots in R by the distance between their lower and upper value and have them ordered from greatest distance to least?

Code:

```
df <- ToothGrowth
df$dose <- as.factor(df$dose)
head(df, 3)

library(dplyr)
df.summary <- df %>%
  group_by(dose) %>%
  summarise(
    lower = min(len), upper = max(len), p = mean(len),
  )

f <- ggplot(
  df.summary,
  aes(x = dose, y = p, ymin = lower, ymax = upper)
)

f + geom_linerange()

```

The goal is to have them ranked from greatest distance to least distance (left to right).

[![Plot](https://i.stack.imgur.com/LLk4f.png)](https://i.stack.imgur.com/LLk4f.png)

Any help at all would be greatly appreciated!

Answer: 
You can use `reorder()`

```
ggplot(
  df.summary,
  aes(x = reorder(dose, -(upper-lower)), y = p, ymin = lower, ymax = upper)) + 
  geom_linerange() + 
  labs(x="Dose")

```

[![toothgrowth](https://i.stack.imgur.com/OA71S.png)](https://i.stack.imgur.com/OA71S.png)
As you can see, there are a number of ways to go about this. In the below case I calculate the difference and order the data.frame according to the result. The last line sets factor levels. This is my preferred way because I keep my ggplots for plotting only and avoid doing any data manipulation if possible.

```
xy.summary$diff <- with(xy.summary, upper - lower)
xy.summary <- xy.summary[order(xy.summary$diff, decreasing = TRUE), ]
levels(xy.summary$dose) <- xy.summary$dose

ggplot(xy.summary, mapping = aes(x = dose, y = p, ymin = lower, ymax = upper)) +
  theme_bw() +
  geom_linerange()

```

[![enter image description here](https://i.stack.imgur.com/O0RXj.png)](https://i.stack.imgur.com/O0RXj.png)