rggplot2ggalt

add a legend to ggalt::geom_dumbbell plot AND sort y axis


In this SO answer, user @Crops shows how to add a legend to a ggalt::geom_dumbbell plot. Very nice.

library(ggalt)

df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))
df2 = tidyr::gather(df, group, value, -trt)

ggplot(df, aes(y = trt)) + 
     geom_point(data = df2, aes(x = value, color = group), size = 3) +
     geom_dumbbell(aes(x = l, xend = r), size=3, color="#e3e2e1", 
                   colour_x = "red", colour_xend = "blue",
                   dot_guide=TRUE, dot_guide_size=0.25) +
     theme_bw() +
     scale_color_manual(name = "", values = c("red", "blue") )

enter image description here

I want to sort trt descending on r. I tried replacing y = trt with y = reorder(trt, r), but I get an error that object r is not found.


Solution

  • Here is a way where we reorder the factor levels of trt in df and df2 before we plot.

    # reorder factor levels
    df$trt <- reorder(df$trt, df$r)
    df2$trt <- factor(df2$trt, levels = levels(df$trt))
    
    ggplot(df, aes(y = trt)) + 
      geom_point(data = df2, aes(x = value, color = group), size = 3) +
      geom_dumbbell(aes(x = l, xend = r), size=3, color="#e3e2e1", 
                    colour_x = "red", colour_xend = "blue",
                    dot_guide=TRUE, dot_guide_size=0.25) +
      theme_bw() +
      scale_color_manual(name = "", values = c("red", "blue") )
    

    enter image description here