如何在ggplot2 stat_function()中传递参数

问题描述 投票:0回答:1

假设我有以下代码:

get_histogram <- function(data_set, column_name, bin_width, attribute_name) {
  ggplot(data_set, aes(x= {{column_name}})) +
    geom_histogram(aes(y= ..density..), binwidth = .3, fill= "lightblue", colour="black") +
    xlab(paste0(attribute_name)) +
    stat_function(fun = dnorm , args= list(mean= mean({{column_name}}), sd= sd({{column_name}})), 
                  mapping = aes(colour = "Normal"))+
    stat_function(fun = dlnorm, args = list(meanlog= mean(log({{column_name}})), sdlog= sd(log({{column_name}}))),
                  mapping = aes(colour = "LogNormal")) + 
    scale_colour_manual("Distribution", values = c("red", "blue"))
}

data <- rnorm(1000, 44, 2)
df <- data.frame(data)
get_histogram(df, data, 1, "Test")

这很好用,对吧?所以,我们知道代码是正确的。

现在,当我在无法在此处共享的数据集上运行相同的代码时,问题就出现了。当我在上面运行第一块代码时,代码运行得很好。我的意思是当我执行以下部分时:

get_histogram_chucnk <- function(data_set, column_name, bin_width, attribute_name) {
  ggplot(data_set, aes(x= {{column_name}})) +
    geom_histogram(aes(y= ..density..), binwidth = .3, fill= "lightblue", colour="black") +
    xlab(paste0(attribute_name)) 
}
get_histogram_chunk(new_df, columnX , 1, "Test")

正如您在这里看到的,我传递了 new_df 和 columnX,它们来自我的真实数据集(正如我之前提到的,不幸的是,我无法共享我的数据)。再一次,这段代码运行得很好。但是,当我运行整个代码时,遇到错误 'object 'columnX' not find.' 在调试时,我发现错误发生在以下行...

stat_function(fun = dnorm , args= list(mean= mean({{column_name}}), sd= sd({{column_name}}))

问题发生在 {{column}} 名称上。 我已经检查了所有内容,并且该代码在第一块代码上运行良好这一事实让我确信问题不在于数据集,而在于 stat_function()

当我在函数外部绘制图形并将列名称和数据框作为硬编码值传递时,此代码也可以正常工作。因此,我确信 stat_function() 不喜欢我传递列名的方式。但是,如果确实如此,为什么它适用于样本数据?

我知道在没有实际数据的情况下很难提供准确的答案,但我们将不胜感激。 PS,columnX 的最小值是 50,所以 logNorm 应该可以正常工作。

r ggplot2 visualization distribution
1个回答
1
投票

如果您将使用

mean({{column_name}})
等内容的位置更改为
mean(data_set[[colname]])
之类的内容,并在代码开头使用
colname = as_label(enquo(column_name))
,它应该可以工作。另外,请注意
..density..
已替换为
after_stat(density)

library(ggplot2)
get_histogram <- function(data_set, column_name, bin_width, attribute_name) {
  require(rlang)
  colname <- as_label(enquo(column_name))
  ggplot(data_set, aes(x= {{ column_name }})) +
    geom_histogram(aes(y= after_stat(density)), binwidth = .3, fill= "lightblue", colour="black") +
    xlab(paste0(attribute_name)) +
    stat_function(fun = dnorm , args= list(mean= mean(data_set[[colname]]), sd= sd(data_set[[colname]])), 
                  mapping = aes(colour = "Normal"))+
    stat_function(fun = dlnorm, args = list(meanlog= mean(log(data_set[[colname]])), sdlog= sd(log(data_set[[colname]]))),
                  mapping = aes(colour = "LogNormal")) + 
    scale_colour_manual("Distribution", values = c("red", "blue"))
}

data <- rnorm(1000, 44, 2)
df <- data.frame(data)
get_histogram(df, data, 1, "Test")
#> Loading required package: rlang

get_histogram(mtcars, mpg, 1, "MPG")

创建于 2023-08-11,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.