D3 Density Distribution script type text javascript src https d3js org d3 v7 min js script script const data 10 10 10 9 10 10 10 10 7 10 10 7 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 0 10 10 10 10 10 10 10 9 10 7 10 10 9 10 9 9 3 9 9 9 9 11 12 Set Dimensions const width 600 const height 600 const margin 40 const xMax width margin 2 const yMax height margin 2 Add svg to the page const svg d3 select body append svg attr width width attr height height append g attr transform translate margin margin const drange d3 extent data d return d let estimator kernelDensityEstimator kernelEpanechnikov 2 d3 ticks drange 0 drange 1 10 let density estimator data console log density density range of our data mins and maxs const xExtent d3 extent density d return d 0 const yExtent d3 extent density d return d 1 x axis const x d3 scaleLinear domain xExtent 0 xExtent 1 range 0 xMax const y d3 scaleLinear domain yExtent 0 yExtent 1 range yMax 0 Add the line svg append path datum density attr fill none attr stroke cc0 attr stroke width 1 5 attr stroke linejoin round attr d d3 line curve d3 curveBasis x function d return x d 0 y function d return y d 1 bottom x axis svg append g attr transform translate 0 yMax call d3 axisBottom x attr color green make bottom axis green left y axis svg append g call d3 axisLeft y function kernelDensityEstimator kernel X return function V return X map function x return x d3 mean V function v return kernel x v function kernelEpanechnikov k return function v return Math abs v k 1 0 75 1 v v k 0 console log ready script
3 scaleLinear domain xExtent 0 xExtent 1 range 0 xMax const y d3 scaleLinear domain yExtent 0 yExtent 1 range yMax 0 Add the line svg append path datum density attr fill none attr stroke cc0 attr stroke width 1 5 attr stroke linejoin round attr d d3 line curve d3 curveBasis x function d return x d 0 y function d return y d 1 bottom x axis svg append g attr transform translate 0 yMax call d3 axisBottom x attr color green make bottom axis green left y axis svg append g call d3 axisLeft y function kernelDensityEstimator kernel X return function V return X map function x return x d3 mean V function v return kernel x v function kernelEpanechnikov k return function v return Math abs v k 1 0 75 1 v v k 0 console log ready script