首页 > 解决方案 > 向 ggplot2 自动绘图功能添加(或覆盖)填充美学

问题描述

我想为自动绘图功能添加填充美学。具体来说,从包到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") 

reprex 包于 2020-11-20 创建(v0.3.0)

问题:我怎样才能为or因素添加fill美感?也就是说,为不同的类别添加一些颜色。TruthPrediction

我尝试过+ scale_fill_manual其他变体,但我不相信在通话fill中使用了美学。autoplot

标签: rggplot2tidymodelsmosaic-plotyardstick

解决方案


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

  • 带有自定义功能
  • autoplot

1.具有自定义功能

autoplot调用的函数是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)

在此处输入图像描述

cm_mosaic_fill(cm, Predicted)

在此处输入图像描述


2. 自动绘图

你也可以直接用它来做autoplot,但在我看来它很棘手,而且不是真正可读或可维护的。

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

在此处输入图像描述

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

在此处输入图像描述


推荐阅读