|
| 1 | +using ScottPlot.Statistics; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using System.Text; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace ScottPlotCookbook.Recipes.Miscellaneous; |
| 9 | + |
| 10 | +public class KernelDensityEstimation : ICategory |
| 11 | +{ |
| 12 | + public Chapter Chapter => Chapter.General; |
| 13 | + public string CategoryName => "Kernel Density Estimation"; |
| 14 | + public string CategoryDescription => "Kernel Density Estimation (KDE) can be used to estimate a PDF for a histogram, allowing the creation of density plots"; |
| 15 | + public class KdeQuickstart : RecipeBase |
| 16 | + { |
| 17 | + public override string Name => "Density Plot"; |
| 18 | + public override string Description => "Density Plots use KDE to estimate a PDF."; |
| 19 | + |
| 20 | + [Test] |
| 21 | + public override void Execute() |
| 22 | + { |
| 23 | + var ys = SampleData.Faithful; |
| 24 | + |
| 25 | + var hist = Histogram.WithBinCount(80, ys); |
| 26 | + |
| 27 | + var histPlot = myPlot.Add.Histogram(hist); |
| 28 | + histPlot.BarWidthFraction = 0.8; |
| 29 | + |
| 30 | + var densityEstimate = hist.Bins.Select((x, i) => KernelDensity.Estimate(x, ys)).ToArray(); |
| 31 | + double scale = ys.Length; |
| 32 | + |
| 33 | + var rescaledDensityEstimate = densityEstimate.Select(x => x * scale).ToArray(); |
| 34 | + |
| 35 | + var scat = myPlot.Add.Scatter(hist.Bins, rescaledDensityEstimate, Colors.Red); |
| 36 | + scat.MarkerSize = 0; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public class KdeKernelOptions : RecipeBase |
| 41 | + { |
| 42 | + public override string Name => "Density Plot Kernels"; |
| 43 | + public override string Description => "Several choices of kernels are available."; |
| 44 | + |
| 45 | + [Test] |
| 46 | + public override void Execute() |
| 47 | + { |
| 48 | + var ys = SampleData.Faithful; |
| 49 | + |
| 50 | + var hist = Histogram.WithBinCount(80, ys); |
| 51 | + |
| 52 | + var histPlot = myPlot.Add.Histogram(hist); |
| 53 | + histPlot.BarWidthFraction = 0.8; |
| 54 | + foreach (var bar in histPlot.Bars) |
| 55 | + { |
| 56 | + bar.FillColor = Colors.LightBlue; |
| 57 | + } |
| 58 | + |
| 59 | + foreach (var kernel in Enum.GetValues<KdeKernel>()) |
| 60 | + { |
| 61 | + var densityEstimate = hist.Bins.Select((x, i) => KernelDensity.Estimate(x, ys, kernel)).ToArray(); |
| 62 | + double scale = ys.Length; |
| 63 | + |
| 64 | + var rescaledDensityEstimate = densityEstimate.Select(x => x * scale).ToArray(); |
| 65 | + |
| 66 | + var scat = myPlot.Add.Scatter(hist.Bins, rescaledDensityEstimate); |
| 67 | + scat.MarkerSize = 0; |
| 68 | + scat.LegendText = kernel.ToString(); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments