1

I am trying to plot a histogram inside a function like this:

norm.plot <- function(col_name, bw) {
  temp_df = pitchbook[!is.na(pitchbook[col_name]), c(col_name)]
  ggplot(temp_df, aes_string(x=col_name))  + 
  geom_histogram(color="blue", fill="cyan", binwidth = bw) + 
  stat_function(fun = function(x) 
    dnorm(x, mean = mean(temp_df[col_name]), sd = sd(temp_df[col_name])) * nrow(temp_df) * bw)
}

But I get an error

argument is not numeric or logical: returning NA
Computation failed in `stat_function()`: 'list' object cannot be coerced to type 'double'

How do I properly input the column name to avoid this error?

shurup
  • 751
  • 10
  • 33
  • 4
    Have a look at the [ggplot2 vignette](https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html#using-aes-and-vars-in-a-package-function-1) – teunbrand Jan 19 '21 at 22:20
  • 2
    by the way - this is the first result when I googled your *exact* question – tjebo Jan 19 '21 at 22:25

1 Answers1

2

Maybe this can help but not tested in lack of data:

#Code
norm.plot <- function(col_name, bw) {
  temp_df = pitchbook[!is.na(pitchbook[col_name]), c(col_name)]
  ggplot(temp_df, aes_string(x=col_name))  + 
  geom_histogram(color="blue", fill="cyan", binwidth = bw)
}
Duck
  • 39,058
  • 13
  • 42
  • 84
  • Thank you! `aes_string` fixed my first issue, but it still yields to problems as I add more to my `ggplot` command. Can you please take a look at my edit above? – shurup Jan 19 '21 at 22:43
  • 1
    @shurup It is better if you compute the mean and sd outside the stat and then pass the values to it like `v1 <- mean(temp_df[col_name])` and then pass `v1` to the stat. – Duck Jan 19 '21 at 22:53