2
df_ex <- read.table("df_example.txt", header=TRUE, sep=" ")

where df_example.txt has the contents of:

name_age age distance
Stu_27 27 6.28
Stu_27 27 5.66
Stu_27 27 5.25
Ben_22 22 3.85
Ben_22 22 4.01
Ben_22 22 4.22
Liz_40 40 3.99
Liz_40 40 4.21
Liz_40 40 4.65

then

ggplot(df_ex, aes(x = distance, y = name_age)) + geom_density_ridges(scale = 1.5, fill="lightblue", rel_min_height=0.00001)

produces a plot as follows enter image description here

How can I order the y-axis by age while still showing the y-axis labels with "name_age" format? The order from bottom to top should be Ben_22 Stu_27 Liz_40

I tried to apply a factor following the ggplot documentation, however when I performed the command

ggplot(df_ex, aes(x = distance, y = factor(name_age, levels=age))) + geom_density_ridges(scale = 1.5, fill="lightblue", rel_min_height=0.00001)

I received an error

Error in `levels<-`(`*tmp*`, value = as.character(levels)) : 
  factor level [2] is duplicated
pogibas
  • 27,303
  • 19
  • 84
  • 117
PhysicalChemist
  • 540
  • 4
  • 14
  • Not related to `ggplot2`, check the `age` vector it contains duplicated values (same problem as here `factor(1, c(1, 1))`), voting to close – pogibas Dec 10 '19 at 16:44
  • Use `reorder` to order a factor by another column. Assuming it's already a factor (`df_ex$name_age = factor(df_ex$name_age)` if it's not), re-order the levels by the mean of the `age` column with `df_ex$name_age = reorder(df_ex$name_age, df_ex$age, FUN = mean)`. – Gregor Thomas Dec 10 '19 at 17:04
  • Thank you @Gregor, it works well. That is indeed a solution if you wish to answer the question. – PhysicalChemist Dec 10 '19 at 17:49
  • I think it's well covered in the FAQs marked as duplicates. – Gregor Thomas Dec 10 '19 at 17:58

0 Answers0