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

1.3k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

1
On

Using the dumbbell package

##Reformat data
df3<-df  %>% arrange(r)

df2<-df%>% mutate("key"="trt")
df2$trt<-factor(df2$trt,df3$trt)

##plot
dumbbell::dumbbell(df2, id="trt", column1="l", column2="r",key="key", delt =1, textsize=3, lab1 = "l", lab2="r", pt_val = 1, pointsize = 3,pt_alpha = 0.6, arrow=1, leg = "Add legend title", pval=2) + xlim(8,85) + facet_wrap(key ~.)

Added in some bells and whistles, you can remove them toggling with the options. I dont have enough points to embed for here is the link. Hope someone finds it useful. dumbbell R Package