我想為 ggplot 中的構面撰寫自定義包裝器,并且在處理變數名時遇到問題。
我想達到的目標:
mtcars %>%
ggplot()
ggh4x::facet_manual(vars(cyl %>%
recode('4' = "four", '6' = "six", '8' = "eight") %>%
factor(levels = c("four", "six", "eight"))),
design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2),
scales = "free")
geom_point(aes(x = disp, y = hp))
現在我想圍繞這個復雜的方面公式構建一個包裝器:
my_facet <- function(x) {
ggh4x::facet_manual(vars(x %>%
recode('4' = "four", '6' = "six", '8' = "eight") %>%
factor(levels = c("four", "six", "eight"))),
design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2),
scales = "free")
}
mtcars %>%
ggplot()
my_facet(x)
geom_point(aes(x = disp, y = hp))
但是由于 x 不在環境中而是在 中mtcars,所以這不起作用:
Error in recode(., `4` = "four", `6` = "six", `8` = "eight") :
object 'x' not found
我嘗試了幾種改變功能x的技巧my_facet,例如sym(x), !!sym(x), enquo(x), {{x}},但沒有任何效果。
這里需要什么樣的變數處理?
uj5u.com熱心網友回復:
這對我有用。你的想法是x <- "cyl"在全域環境中參考一個變數嗎?
my_facet <- function(x) {
ggh4x::facet_manual(vars( {{x}} %>%
recode('4' = "four", '6' = "six", '8' = "eight") %>%
factor(levels = c("four", "six", "eight"))),
design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2),
scales = "free")
}
mtcars %>%
ggplot()
my_facet(cyl)
geom_point(aes(x = disp, y = hp))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522762.html
