r - 向 ggplot2 自动绘图功能添加(或覆盖)填充美学
问题描述
我想为自动绘图功能添加填充美学。具体来说,从包到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 包于 2020-11-20 创建(v0.3.0)
问题:我怎样才能为or因素添加fill
美感?也就是说,为不同的类别添加一些颜色。Truth
Prediction
我尝试过+ scale_fill_manual
其他变体,但我不相信在通话fill
中使用了美学。autoplot
解决方案
我将向您展示两种获得所需结果的方法:
- 带有自定义功能
- 和
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")
推荐阅读
- javascript - 'Slick' 轮播 JQuery 代码无法运行/加载
- r - geom_bar 的 geom_text 位置问题
- dart - dart2native 可执行文件可以在 AppStore 和 MicrosoftStore 上发布吗?
- ios - 有什么方法可以在 coreData 中存储多维数组?
- javascript - 从孩子访问 useState 钩子
- python - 如何在 Keras 的 LSTM 中修复以下错误?如果 RNN 是有状态的,请指定 `batch_input_shape`
- python - 模型为每个观察输出 0 个概率和 0 个类别
- reactjs - 通过渲染的 React 组件创建新行
- api - Google Fit REST API 上的数据源创建问题(氧饱和度)
- php - 是否可以在不写入文件的情况下创建包含二进制数据的文件?