I would like to add a fill aesthetic to an autoplot function. Specifically, to the autoplot.conf_mat
function from the yardstick
package.
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")
Created on 2020-11-20 by the reprex package (v0.3.0)
QUESTION: How can I add a fill
aesthetic to either the Truth
or Prediction
factor? That is, add some color to the different categories.
I have tried + scale_fill_manual
and other variants, but I do not believe a fill
aesthetic is being utilized in the autoplot
call.
I'll show you two ways to get the result you want:
autoplot
The function that autoplot
calls is cs_mosaic
.
You can rewrite that function to add the labels you need, in this way:
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)
You can do it directly with autoplot
too, but it's tricky and not really readable or maintainable in my opinion.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.