首页 > 解决方案 > 带有图例的 R 哑铃图,无法对 y 轴进行排序

问题描述

我正在尝试在 R 中构建一个哑铃图,其中包括一个图例和按 y 轴以外的值排序的能力。

我可以在 2 个单独的图中单独获得这些要求,但无法在一个图表中同时使用这两个功能。

这是显示带有图例且没有自定义排序的图的脚本:

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

这是显示没有图例和自定义排序的情节的脚本:

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=reorder(trt,-l), x=l, xend=r)) + 
  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") )

当我尝试将两者相加时,我收到错误“tapply 中的错误(X = X,INDEX = x,FUN = FUN,...):参数必须具有相同的长度”下面是我正在使用的脚本:

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=reorder(trt,-l), x=l, xend=r)) + 
  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

解决方案


设法弄清楚这一点。

只需添加以下行:

  geom_point(size=5, aes(x = r, color = "Blue"))+
  geom_point(size=5, aes(x = l, color = "Red"))+

完整脚本:

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=reorder(trt,-l), x=l, xend=r)) + 
  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) +

  geom_point(size=5, aes(x = r, color = "Blue"))+
  geom_point(size=5, aes(x = l, color = "Red"))+

  theme_bw() +
  scale_color_manual(name = "", values = c("red", "blue") )

推荐阅读