ggplot2 带有空格和 tidyeval 语法的变量名

ggplot2 Variable Name with Spaces and tidyeval Syntax

我正在尝试创建一个允许用户传入列名的函数,但我发现生成的图只是屏幕中间的一个点。需要更改什么才能使其按预期工作?我的极简示例是:

library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
                      `High Temperature` = seq(30, 22, -2), check.names = FALSE)

xVariable <- "Month"
yVariable <- "High Temperature"
yVariable <- enquo(yVariable)
ggplot(weather, aes(x = xVariable, y = !!yVariable)) + geom_point()

因为它是引用的文本,而不是 enquo,所以使用 rlang::sym

xVariable <- "Month"
yVariable <- "High Temperature"
fun <- function(dat, xvar, yvar) {
  xvar <- rlang::sym(xvar)
  yvar <- rlang::sym(yvar)
  p1 <-dat %>%
    ggplot(aes(x = !!xvar, y = !!yvar)) +
    geom_point()
  return(p1)
  
}


fun(weather, xVariable, yVariable)

您可以使用 aes_string 而不是 aes

library(ggplot2)
weather <- data.frame(Month = month.name[1:5], `Low Temperature` = 20:16,
                      `High Temperature` = seq(30, 22, -2), check.names = FALSE)

xVariable <- "Month"
yVariable <- "`High Temperature`"

ggplot(weather, aes_string(x = xVariable, y = yVariable)) + geom_point()

请注意,enquo() 用于函数参数。

如果您将列名称作为字符串,请使用 .data 代词:

fn <- function(data, x, y) {
  data %>%
    ggplot(aes(x = .data[[x]], y = .data[[y]])) +
    geom_point() 
}

x <- "disp"
y <- "drat"

fn(mtcars, x, y)