Best way to plot smooth normal distribution in ggplot

我的未来我决定 提交于 2021-02-05 06:55:46

问题


I would like to plot a nice, 'approaching the limit'-looking normal pdf in ggplot.

I found that to get a very symmetric and clean looking plot, I had to crank up the number of samples to a rather large number; one million creates a great visualization. However, this is pretty slow, especially if I hope to work with Shiny at some point.

df <- data.frame(c(rnorm(1000000)))
ggplot(df, aes(df[1])) + geom_density()

Surely there is a better way to display something close to the ideal normal distribution?


回答1:


Basically, your code should look like:

 ggplot(data=dataset, aes(dataset$value)) +
      stat_function(fun = dnorm, args = c(mean = mean(dataset$value), sd = sd(dataset$value)))

stat_function uses the dnorm function (to get the density of a normal variable) parses in the mean & median values and plots the normal distribution.

Reference : How dnorm works?

For ggplot stat_function Documentation follow this link Sample : https://github.com/tidyverse/ggplot2/blob/master/R/stat-function.r



来源:https://stackoverflow.com/questions/26683286/best-way-to-plot-smooth-normal-distribution-in-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!