我看到了“將變數填充到 ggplot”問題的答案:R - 如何在閃亮中使用 selectInput 來更改 x 并填充 ggplot 渲染圖中的變數?
我怎樣才能對 stat_function 做類似的事情?
這是我在渲染圖中的代碼:
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)
我得到了直方圖和警告:
Warning in mean.default(input$x, na.rm = TRUE) : argument is not numeric or logical: returning NA
uj5u.com熱心網友回復:
問題是這input$x是一個字符,因此mean(input$x, na.rm = TRUE)不起作用。相反,您可以這樣做mean(removeNA[[input$x]], na.rm = TRUE)。
使用的最小表示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`.

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450747.html
