繁体   English   中英

向 ggplot2 自动绘图功能添加(或覆盖)填充美感

[英]Add (or override) fill aesthetic to a ggplot2 autoplot function

我想为自动绘图功能添加填充美感。 具体而言,向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 包(v0.3.0) 于 2020 年 11 月 20 日创建

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

我已经尝试过+ scale_fill_manual和其他变体,但我认为autoplot调用中没有使用fill美学。

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

  • 带有自定义功能
  • 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")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM