代码之家  ›  专栏  ›  技术社区  ›  JasonAizkalns

向ggplot2 autoplot函数添加(或重写)填充

  •  0
  • JasonAizkalns  · 技术社区  · 4 年前

    我想给autoplot函数添加一个填充美学。具体来说,就是 autoplot.conf_mat yardstick 包裹。

    library(tidyverse)
    library(tidymodels)
    
    data("hpc_cv")
    
    cm <- hpc_cv %>%
      filter(Resample == "Fold01") %>%
      conf_mat(obs, pred)
    cm
    #>           Truth
    #> Prediction  VF   F   M   L
    #>         VF 166  33   8   1
    #>         F   11  71  24   7
    #>         M    0   3   5   3
    #>         L    0   1   4  10
    
    autoplot(cm, type = "mosaic") 
    

    于2020年11月20日由 reprex package (第0.3.0版)

    问题:如何添加 fill 美感 Truth Prediction 因素?也就是说,为不同的类别添加一些颜色。

    我试过了 + scale_fill_manual 和其他变种,但我不相信 填满 美学在现代社会中得到了广泛的应用 autoplot 打电话。

    0 回复  |  直到 4 年前
        1
  •  4
  •   Edo    4 年前

    我将向您展示两种获得所需结果的方法:

    • 使用自定义函数
    • 具有 autoplot

    1使用自定义函数

    自动绘图 电话是 cs_mosaic .

    您可以重写该函数以添加所需的标签,方法如下:

    cm_mosaic_fill <- function(x, fill){
     
     `%+%` <- ggplot2::`%+%`
     cm_zero <- (as.numeric(x$table == 0)/2) + x$table
     x_data <- yardstick:::space_fun(colSums(cm_zero), 200)
     full_data_list <- purrr::map(seq_len(ncol(cm_zero)), 
                                  ~yardstick:::space_y_fun(cm_zero, .x, x_data))
     full_data <- dplyr::bind_rows(full_data_list)
     y1_data <- full_data_list[[1]]
     tick_labels <- colnames(cm_zero)
     
     ####### { EDIT: add fill
     full_data$Predicted <- tick_labels
     full_data$Truth     <- rep(tick_labels, each = nrow(x_data))
     ####### }
    
     ggplot2::ggplot(full_data) %+% 
      ggplot2::geom_rect(ggplot2::aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, 
    
      ####### { EDIT: add fill
                         fill = !!enquo(fill))) %+%
      ####### }
    
      ggplot2::scale_x_continuous(breaks = (x_data$xmin + x_data$xmax)/2, labels = tick_labels) %+% 
      ggplot2::scale_y_continuous(breaks = (y1_data$ymin + y1_data$ymax)/2, labels = tick_labels) %+% 
      ggplot2::labs(y = "Predicted", x = "Truth") %+% 
      ggplot2::theme(panel.background = ggplot2::element_blank())
     
    }
    
    cm_mosaic_fill(cm, Truth)
    

    enter image description here

    cm_mosaic_fill(cm, Predicted)
    

    enter image description here


    2带自动绘图

    你可以直接用 自动绘图 但在我看来,它很棘手,不太可读或可维护。

    autoplot(cm, type = "mosaic") + aes(fill = rep(colnames(cm$table), each = ncol(cm$table))) + labs(fill = "Truth")
    

    enter image description here

    autoplot(cm, type = "mosaic") + aes(fill = rep(colnames(cm$table), ncol(cm$table))) + labs(fill = "Predicted")
    

    enter image description here