添加图例到 ggalt::geom_dumbbell plot AND sort y axis

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

中,用户@Crops 展示了如何将图例添加到 ggalt::geom_dumbbell 图中。非常好。

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") )

我想按 r 降序排列 trt。我尝试用 y = reorder(trt, r) 替换 y = trt,但我收到一个错误,指出找不到对象 r

这是我们在绘图之前对 dfdf2trt 的因子水平重新排序的方法。

# 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") )

使用哑铃包

##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 ~.)

添加了一些花里胡哨的东西,您可以通过选项将它们移除。 我没有足够的积分来嵌入这里是 link。希望有人觉得它有用。