在ggalt :: geom_dumbbell图中添加图例并对y轴进行排序

时间:2018-11-11 12:35:15

标签: r ggplot2

this SO answer中,用户@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") )

enter image description here

我想对trt降序的r进行排序。我尝试将y = trt替换为y = reorder(trt, r),但收到一个错误消息,找不到对象r

2 个答案:

答案 0 :(得分:2)

这是一种在绘制之前对trtdfdf2的因子水平进行重新排序的方法。

# 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 :(得分:0)

使用哑铃包

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

添加了一些花里胡哨的功能,您可以通过切换选项来删除它们。 我没有足够的积分来嵌入这里是链接。希望有人觉得它有用。 dumbbell R Package