簡體   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