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

时间:2019-07-12 14:32:37

标签: 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"
          ))

问题:

我想在散点图中显示数据,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)

Example plot

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

任何帮助将不胜感激,

Matthias

3 个答案:

答案 0 :(得分:4)

可重新订购:

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

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

enter image description here

答案 1 :(得分:2)

尝试forcats::fct_reorder()

例如:

data %>% 
  ggplot(aes(x = auc, y = forcats::fct_reorder(study, as.numeric(tool)))) + 
  geom_point(aes(color = tool), size = 4)

n.b。用工具刻面可能会提供更多信息。例如

data %>% 
  ggplot(aes(x = auc, y = forcats::fct_reorder(study, auc))) + 
  geom_point(size = 4) +
  facet_wrap(~tool)

答案 2 :(得分:2)

做与上述乔恩(Jon)相同的工作,但另一种方法是按照给定的顺序来研究研究名称,并以此来对绘图进行排序:

levels <- data %>% 
  arrange(tool, study, year) %>% pull(study)

data %>% 
  mutate(study = factor(study, levels = unique(levels))) %>% 
  ggplot(aes(x = auc, y = study)) + 
  geom_point(aes(color = tool), size = 4)

您的Fass (2008)点有点棘手,将两个工具合并在同一行上。这是故意的吗?

enter image description here