3
$\begingroup$

I'm looking to use the Manipulate command to take a distribution with multiple parameters (e.g., mean and sigma for the normal), generate some variates, then plot the density with kernel smoothing. Ideally I'd like to have sliders for all parameters, the number of variates used, and the bandwidth for smoothing.

Here's what I've got:

Manipulate[
  Plot[
    SmoothKernelDistribution[RandomVariate[NormalDistribution[μ, σ], numbVars], bw],
    {x, -5, 5}],
  {μ, -1, 1},
  {σ, 0, 5},
  {numVars, 10, 1000, 10},
  {bw, .1, 5}]

But it looks like I'm not indicating things correctly, getting errors for the RandomVariate parameters and for SmoothKernelDistribution and perhaps others that are supressed.

$\endgroup$
2
  • $\begingroup$ Welcome to our site, Matt! I would like to suggest that first you read our faq and then respond to its suggestions by showing what you have done so far (with examples of your code). Otherwise your question might be (mis?)interpreted as a request for free coding services, which is not what this community is about. $\endgroup$
    – whuber
    Mar 15, 2013 at 16:53
  • 1
    $\begingroup$ @whuber No problem I figured someone might already done something similar, I'll share what I've got so far. $\endgroup$
    – Matt Asher
    Mar 15, 2013 at 17:00

1 Answer 1

9
$\begingroup$

Something like the following should get you started. I use KernelMixtureDistribution with the setting MaxMixtureKernels set to All because it works symbolically and is not an approximation to the kernel density estimator like SmoothKernelDistribution.

Manipulate[
 Block[{data, dist, kmd},
  SeedRandom[1];
  data = RandomVariate[dist = NormalDistribution[μ, σ], n];
  kmd = KernelMixtureDistribution[data, h, MaxMixtureKernels -> All];
  Plot[{PDF[dist, x], PDF[kmd, x]}, {x, -xRng, xRng}, PlotRange -> All]
  ]
  , {{μ, 0}, -1, 1}, {{σ, 1}, 0.01, 
  5}, {{n, 100}, {10, 100, 1000, 10000}}, {{xRng, 5}, 1, 
  10}, {{h, .5}, 0.01, 1}
]

enter image description here

Note that in Mathematica these nonparametric density estimators are actually distributions so we need to plot the PDF not just the distribution itself. The benefit is that all other distribution properties like random number generation work too.

$\endgroup$
2
  • $\begingroup$ Hi Andy thanks for the solution! What do I change to get the variates to be resampled when I make a change to the sliders? $\endgroup$
    – Matt Asher
    Mar 15, 2013 at 17:29
  • $\begingroup$ Remove the SeedRandom[1]. I put it there specifically to fix the random numbers so it doesn't bounce around when you move any slider. $\endgroup$
    – Andy Ross
    Mar 15, 2013 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.