我将向您展示两种获得所需结果的方法:
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")