Home > front end >  How to fill in the variables into the stat_funciton() programmatically?
How to fill in the variables into the stat_funciton() programmatically?

Time:03-25

I saw the answer to the question to "filling in the variables into ggplot": R - How do I use selectInput in shiny to change the x and fill variables in a ggplot renderPlot?

How can I do similar things to stat_function?

Here's my code in side the renderPlot:

ggplot(data = removedNA,mapping = aes_string(x = input$x))    
  geom_histogram(aes(y = ..density..))      
  stat_function(fun = dnorm, n = 40000, args = list(mean = mean(input$x, na.rm = TRUE), sd = sqrt(var(input$x,na.rm = TRUE))))  
  labs(title = input$x) 

I got the histogram and a Warning: Warning in mean.default(input$x, na.rm = TRUE) : argument is not numeric or logical: returning NA

CodePudding user response:

The issue is that input$x is a character and hence mean(input$x, na.rm = TRUE)will not work. Instead you could do mean(removeNA[[input$x]], na.rm = TRUE).

A minimal reprex using mtcars:

library(ggplot2)

removeNA <- mtcars

input <- list(
  x = "mpg"
)

mean_x <- mean(removeNA[[input$x]], na.rm = TRUE)
sd_x <- sqrt(var(removeNA[[input$x]],na.rm = TRUE))

ggplot(data = removeNA, mapping = aes_string(x = input$x))    
  geom_histogram(aes(y = ..density..))      
  stat_function(fun = dnorm, n = 40000, args = list(mean = mean_x, sd = sd_x))  
  labs(title = input$x) 
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

  • Related