向ggalt :: geom_dumbbell图中添加图例并对y轴进行排序 [英] add a legend to ggalt::geom_dumbbell plot AND sort y axis

查看:107
本文介绍了向ggalt :: geom_dumbbell图中添加图例并对y轴进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此SO答案中,用户@Crops显示了如何在ggalt::geom_dumbbell图中添加图例.很不错.

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

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

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.

推荐答案

这里是一种在绘制之前重新排序dfdf2trt因子水平的方法.

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

这篇关于向ggalt :: geom_dumbbell图中添加图例并对y轴进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆