[英]Add (or override) fill aesthetic to a ggplot2 autoplot function
I would like to add a fill aesthetic to an autoplot function.我想为自动绘图功能添加填充美感。 Specifically, to the
autoplot.conf_mat
function from the yardstick
package.具体而言,向
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")
Created on 2020-11-20 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2020 年 11 月 20 日创建
QUESTION: How can I add a fill
aesthetic to either the Truth
or Prediction
factor?问题:如何为
Truth
或Prediction
因素添加fill
美感? 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.我已经尝试过
+ scale_fill_manual
和其他变体,但我认为autoplot
调用中没有使用fill
美学。
I'll show you two ways to get the result you want:我将向您展示两种获得您想要的结果的方法:
autoplot
autoplot
The function that autoplot
calls is cs_mosaic
. autoplot
调用的函数是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
,但在我看来它很棘手,而且不是真正可读或可维护的。
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.