[英]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 日創建
問題:如何為Truth
或Prediction
因素添加fill
美感? 也就是說,為不同的類別添加一些顏色。
我已經嘗試過+ scale_fill_manual
和其他變體,但我認為autoplot
調用中沒有使用fill
美學。
我將向您展示兩種獲得您想要的結果的方法:
autoplot
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)
你也可以直接用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.