【问题标题】:Wrong axis label while passing column name in ggplot function在 ggplot 函数中传递列名时轴标签错误
【发布时间】:2020-02-20 12:10:23
【问题描述】:

在下面的示例中,我将数据集的列名传递给使用 ggplot 的函数。 该函数可以提取列名并成功绘制图形但轴标签错误

library(tidyverse)
attach(mpg)

plot_func <- function(col_name) {
  ggplot(mpg,aes(x = col_name, fill = class)) +
    geom_bar() 
}

plot_func(drv)

是否可以将 x 轴标签从 col_name 更改为 drv。我尝试了以下方法,但它不起作用。

plot_func("drv")

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    你只需要在你的函数中使用get(),这样它就可以在aes(中被识别为变量,而在xlab()中被识别为字符串:

    library(tidyverse)
    attach(mpg)
    
    plot_func <- function(col_name) {
      ggplot(mpg,aes(x = get(col_name), fill = class)) +
        geom_bar() +
        xlab(col_name)
    }
    
    plot_func("drv")
    

    【讨论】:

    • 谢谢 - 但这种方法仍然没有将 x 标签更改为 drv?
    【解决方案2】:

    如果您首先将drv 作为字符串传递,然后将其取消引用,则可以将其作为字符串传递。

    library(tidyverse)
    attach(mpg)
    
    plot_func <- function(col_name) {
      col_name <- rlang::sym(col_name)
      ggplot(mpg,aes(x = !!col_name, fill = class)) +
        geom_bar() 
    }
    
    plot_func("drv")
    

    【讨论】:

    • 谢谢!在我的真实数据集中(不容易提供可重现的示例),我收到以下错误:“只有字符串可以转换为符号”该字段的数据类型是 chr。发生这种情况有什么原因吗?
    猜你喜欢
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多