如何使用ggplot通过第三个分组变量对散点图中的离散变量进行排序?

Mat*_*ias 2 r ggplot2

最小可重复示例:

我有以下简单的数据表(用 生成dput()):

data <- structure(list(study = c("Brennan (2009)", "Farabee (2010)", 
                         "Fass (2008)", "Mills (2007)", "Fass (2008)", "Howard (2013)", 
                         "Latessa (2017)", "Lovins (2018)", "Lowenkamp (2015)", "Allan (2006)", 
                         "Endrass (2009)", "Looman (2006)", "Retterberg (2006)", "Sreenivasan (2007)"), 
               year = c(2009, 2010, 2008, 2007, 2008, 2013, 2017, 2018, 2015, 
                        2006, 2009, 2006, 2006, 2007), 
               tool = structure(c(1L, 1L, 1L, 
                                  2L, 3L, 4L, 5L, 5L, 6L, 7L, 7L, 7L, 7L, 7L), 
                                .Label = c("COMPAS", 
                                           "HCR-20", "LSI-R", "OASys", "ORAS", "PCRA", "Static-99"), class = "factor"), 
               auc = c(0.66, 0.7, 0.53, 0.72, 0.6, 0.72, 0.6, 0.66, 0.73, 
                       0.78, 0.76, 0.63, 0.74, 0.62)), 
          row.names = c(NA, -14L), .Names = c("study", 
                                              "year", "tool", "auc"), 
          class = c("tbl_df", "tbl", "data.frame"
          ))
Run Code Online (Sandbox Code Playgroud)

问题:

我想在散点图中显示数据,y 轴为“study”,x 轴为“auc”。我还想按“工具”对数据进行分组(即,以不同的颜色显示每个工具)。尽管一切正常,但我无法通过分组变量“工具”对离散 y 轴进行排序(请参见下面的示例)。

例子:

library(dplyr)
library(ggplot2)
###################

arrange(data, tool, study, year) %>%
ggplot(aes(x = auc, y = study)) + 
       geom_point(aes(color = tool), size = 4)

Run Code Online (Sandbox Code Playgroud)

示例图

如您所见,每个点的顺序由“研究”定义。但是,我希望由“工具”定义顺序,以便所有具有相同颜色的点都在彼此下方。我已经阅读了一些关于reorder()and 的stackoverflow 帖子rev(),但没有发现它们对我的特定问题有帮助,因为它们没有按第三个分组变量对数据进行排序。

任何帮助都感激不尽,

马蒂亚斯

Jan*_*ary 5

重新排序:

data %>% mutate(study=reorder(study, as.numeric(tool))) %>% 
  ggplot(aes(x = auc, y = study)) +  
  geom_point(aes(color = tool), size = 4)
Run Code Online (Sandbox Code Playgroud)

说明:使用reorder您将研究转换为一个因子,从而在 ggplot 上强制执行某个顺序。顺序由 给出as.numeric(tool)。我们必须将其转换为数值向量,因为tool它不是有序因子。

在此处输入图片说明