truncated-normal-distribution-density-function.tex 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. % used PGFPlots v1.14
  2. % (inspired by Jake's answer given here
  3. % <http://tex.stackexchange.com/a/340939/95441>)
  4. \documentclass[border=5pt]{standalone}
  5. \usepackage{pgfplots}
  6. \pgfplotsset{
  7. compat=1.3,
  8. }
  9. % create cycle lists that uses the style from OPs figure
  10. % <https://upload.wikimedia.org/wikipedia/en/d/df/TnormPDF.png>
  11. \pgfplotscreateplotcyclelist{line styles}{
  12. black,solid\\
  13. blue,dashed\\
  14. red,dotted\\
  15. orange,dashdotted\\
  16. }
  17. % define a command which stores all commands that are needed for every
  18. % `raw gnuplot' call
  19. \newcommand*\GnuplotDefs{
  20. % set number of samples
  21. set samples 50;
  22. %
  23. %%% from <https://en.wikipedia.org/wiki/Normal_distribution>
  24. % cumulative distribution function (CDF) of normal distribution
  25. cdfn(x,mu,sd) = 0.5 * ( 1 + erf( (x-mu)/sd/sqrt(2)) );
  26. % probability density function (PDF) of normal distribution
  27. pdfn(x,mu,sd) = 1/(sd*sqrt(2*pi)) * exp( -(x-mu)^2 / (2*sd^2) );
  28. % PDF of a truncated normal distribution
  29. tpdfn(x,mu,sd,a,b) = pdfn(x,mu,sd) / ( cdfn(b,mu,sd) - cdfn(a,mu,sd) );
  30. }
  31. \begin{document}
  32. \begin{tikzpicture}
  33. % define macros which are needed for the axis limits as well as for
  34. % setting the domain of calculation
  35. \pgfmathsetmacro{\xmin}{0}
  36. \pgfmathsetmacro{\xmax}{1}
  37. \begin{axis}[
  38. xmin=\xmin,
  39. xmax=\xmax,
  40. ymin=0,
  41. %ymax=0.23,
  42. %ytick distance=0.05,
  43. %enlargelimits=0.05,
  44. no markers,
  45. smooth,
  46. % use the above created cycle list ...
  47. cycle list name=line styles,
  48. % ... and append the following style to all `\addplot' calls
  49. every axis plot post/.append style={
  50. very thick,
  51. },
  52. yticklabel style={
  53. /pgf/number format/.cd,
  54. fixed,
  55. fixed zerofill,
  56. precision=2,
  57. },
  58. xlabel={x},
  59. ylabel={probability density},
  60. ]
  61. \addplot gnuplot [raw gnuplot] {
  62. % first call all the "common" definitions
  63. \GnuplotDefs
  64. % and then create the data tables
  65. % in GnuPlot `x` key is identical to PGFPlots `domain` key
  66. plot [x=\xmin:\xmax] tpdfn(x,0.8,0.3, 0, 1);
  67. };
  68. \addplot gnuplot [raw gnuplot] {
  69. \GnuplotDefs
  70. plot [x=\xmin:\xmax] tpdfn(x,0.7,0.1, 0, 1);
  71. };
  72. \end{axis}
  73. \end{tikzpicture}
  74. \end{document}