向R中的ggalt :: geom_dumbbell中的哑铃图添加传统图例 [英] Adding a traditional legend to dumbbell plot in `ggalt::geom_dumbbell` in `R`

查看:157
本文介绍了向R中的ggalt :: geom_dumbbell中的哑铃图添加传统图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在使用 R ggalt :: geom_dumbbell 创建的哑铃图中添加传统图例?



解决方案

一种方法获得图例的方法是基于长格式的数据集添加一个点图层,将颜色映射到分组变量。



首先,通过 tidyr 中的 gather 创建长格式数据集。

  df2 = tidyr :: gather(df,group,value,-trt)

然后绘制图,添加带有长数据集的新点层并使用 scale_color_manual 设置颜色。我将 geom_dumbbell 特定的美学元素移到了该层中。

  ggplot(df,aes(y = trt))+ 
geom_point(data = df2,aes(x =值,颜色=组),大小= 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) )


How to add a traditional legend to dumbbell plot created using ggalt::geom_dumbbell in R?

This question has an answer with an in-chart legend. How to map the aesthetics to get a separate legend for the points on the side/bottom ?

library(ggalt)

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

ggplot(df, aes(y=trt, x=l, xend=r)) + 
  geom_dumbbell(size=3, color="#e3e2e1", 
                colour_x = "red", colour_xend = "blue",
                dot_guide=TRUE, dot_guide_size=0.25) +
  theme_bw()

解决方案

One way to get a legend is to add a points layer based on the dataset in long format, mapping color to the grouping variable.

First, make a long format dataset via gather from tidyr.

df2 = tidyr::gather(df, group, value, -trt)

Then make the plot, adding the new points layer with the long dataset and using scale_color_manual to set colors. I moved the geom_dumbbell specific aesthetics into that layer.

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中的ggalt :: geom_dumbbell中的哑铃图添加传统图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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