R 在函数内更改ggplot中的图例顺序

R 在函数内更改ggplot中的图例顺序,r,ggplot2,rlang,quasiquotes,R,Ggplot2,Rlang,Quasiquotes,我想在函数中绘制一个数据帧。图例应以特定方式订购。在我的例子中,为了保持简单,我只是颠倒顺序。我实际上想选择一个特定的行并将其推到图例的最后一个位置 顺便说一下,我正在创建一个新的R包,如果这在任何方面都是相关的 在函数外绘图 函数内部的绘图 最简单的方法就是使用变量,这显然不起作用 f1 <- function(myvariable) { iris$myvariable <- factor(iris$myvariable, levels = rev(levels(iris$my

我想在函数中绘制一个数据帧。图例应以特定方式订购。在我的例子中,为了保持简单,我只是颠倒顺序。我实际上想选择一个特定的行并将其推到图例的最后一个位置

顺便说一下,我正在创建一个新的R包,如果这在任何方面都是相关的

在函数外绘图

函数内部的绘图

最简单的方法就是使用变量,这显然不起作用

f1 <- function(myvariable) {
  iris$myvariable <- factor(iris$myvariable, levels = rev(levels(iris$myvariable)))
  p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, fill = Species) ) +
    geom_bar( stat = "identity")
  p
}
f1("Species")

 #> Error in `$<-.data.frame`(`*tmp*`, myvariable, value = integer(0)) : 
  replacement has 0 rows, data has 150 
我尝试使用准旋转,但这种方法只能绘制数据帧。我还不能颠倒顺序

library(rlang)
# Only plotting works
f2 <- function(myvariable) {
  v1 <- ensym(myvariable)
  p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, fill = eval(expr(`$`(iris, !!v1))))) +
    geom_bar( stat = "identity")
  p
}
f2("Species")

# This crashes
f3 <- function(myvariable) {
  v1 <- ensym(myvariable)
  expr(`$`(iris, !!v1)) <- factor(expr(`$`(iris, !!v1)), levels = rev(levels(expr(`$`(iris, !!v1)))))
  p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, fill = eval(expr(`$`(iris, !!v1))))) +
    geom_bar( stat = "identity")
  p
}
f3("Species")

#> Error in `*tmp*`$!!v1 : invalid subscript type 'language'
所以主要的问题是,我不能用准旋转来分配一些东西。

有几件事:

您可以使用[[而不是$]以编程方式访问数据帧列。 您可以使用ggplot的aes_字符串在R CMD检查期间最小化注释,因为您提到您正在执行一个包。 您可以从package for Cats中使用fct_relevel将因子级别发送到末尾。 也就是说:

f <- function(df, var) {
  lev <- levels(df[[var]])
  df[[var]] <- forcats::fct_relevel(df[[var]], lev[1L], after = length(lev) - 1L)

  ggplot(df, aes_string(x = "Sepal.Width", y = "Sepal.Length", fill = var)) +
    geom_bar(stat = "identity")
}

f(iris, "Species")
有几件事:

您可以使用[[而不是$]以编程方式访问数据帧列。 您可以使用ggplot的aes_字符串在R CMD检查期间最小化注释,因为您提到您正在执行一个包。 您可以从package for Cats中使用fct_relevel将因子级别发送到末尾。 也就是说:

f <- function(df, var) {
  lev <- levels(df[[var]])
  df[[var]] <- forcats::fct_relevel(df[[var]], lev[1L], after = length(lev) - 1L)

  ggplot(df, aes_string(x = "Sepal.Width", y = "Sepal.Length", fill = var)) +
    geom_bar(stat = "identity")
}

f(iris, "Species")