1

Let's consider my ggplot function for histogram:

library(ggplot2)
get_histogram <- function(vec, width) {
  df <- data.frame(vec)
  temp <- ggplot2::ggplot(df, aes(x = vec)) +
    # Delete x axis name and add plot title
    labs(
      x = NULL,
      title = "Empirical histogram vs standard normal density"
    ) +
    # Center plot title
    theme(plot.title = element_text(hjust = 0.5)) +
    # Add histogram with respect to given bin width
    geom_histogram(
      binwidth = width,
      aes(y = stat(density)),
      fill = I("blue"),
      col = I("red"),
      alpha = I(.2)
    ) +
    # Adding probability density function of standard normal distribution.
    stat_function(fun = function(x) {
      stats::dnorm(x, mean = 0, sd = 1)
    })
  temp
}

Let's see how it works:

get_histogram(rnorm(100), width = 0.4)

enter image description here

However I will see error:

no visible binding for global variable 'density'

when running pacakge checks. Do you know where is the problem? I tried to find it, but it seems that most of those errors is connected with dplyr package rather than ggplot

John
  • 1,849
  • 2
  • 13
  • 23
  • sounds like you need to put `stats::density` in your code in `geom_histogram` or import density from stats. – user12728748 Jun 08 '21 at 13:09
  • Unfortunately function crashes when `stats::density` was added – John Jun 08 '21 at 13:20
  • 1
    Perhaps you could define `density = NULL` in your function prior to the ggplot code, and use the rest of your code as before, then it might not complain. – user12728748 Jun 08 '21 at 13:43
  • Maybe this helps: https://stackoverflow.com/questions/9439256/how-can-i-handle-r-cmd-check-no-visible-binding-for-global-variable-notes-when. I'm using the `.data` pro-noun from `rlang` when using `dplyr` or `ggplot2` or ... in packages. – stefan Jun 08 '21 at 14:03
  • 1
    Seconding the `.data` comment. That is also referenced when generally speaking about this type of error message [in a note over at r-bloggers](https://www.r-bloggers.com/2019/08/no-visible-binding-for-global-variable/). I'm not seeing any issue or message when I run your code, so it could be another package you are loading or a versioning issue. – chemdork123 Jun 08 '21 at 14:23

0 Answers0