r - 带有图例的 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") )
任何想法如何纠正这个问题?谢谢
解决方案
设法弄清楚这一点。
只需添加以下行:
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") )
推荐阅读
- sql - 在“IN”子句中使用列名时有什么注意事项吗?
- angular - mat-menu 穿透“cdk 覆盖雾”
- java - 将 Google Signin 集成到现有 OAuth
- npm - npm install 似乎安装太多
- php - 在 wordpress admin 中访问自定义文件夹文件
- javascript - 文档更改时未调用 Ajax 函数
- git - 忽略文件夹但在 Git 上不递归
- swift - iOS - 集合视图是否将每个单元格保留在内存中?
- ag-grid - 如何使用复杂对象设置行数据
- perl - Perl 将 UTC MySQL 日期时间格式化为 GMT/BST 伦敦/欧洲字符串