Tobal Tobal - 3 years ago 174
Javascript Question

Plotting normal density function with d3 js

I'm trying to plot this continuous function with D3 js version 4 but i'm having many problems with arrays. this is my javascript code:



var x = d3.range(-4., 4.1, 0.1)
var fnorm = x => (1. / Math.sqrt(2 * Math.PI)) * Math.exp(-0.5 * Math.pow(x, 2))
var y = new Array()
for (var i = 0 ; i < x.length ; i++) {
y[i] = fnorm(x[i])
}

var dataset = []
for (var j = 0; j < x.length; j++) {
dataset[j] = []
dataset[j][0] = x[j]
dataset[j][1] = y[j]
}
console.log(dataset[0])
console.log(dataset[1])
var w = 500
var h = 500
var padding = 50

var xScale = d3.scaleLinear()
.domain([d3.min(x, function(d) { return d }), d3.max(x, function(d) { return d })])
.range([padding, w - padding * 2])

var yScale = d3.scaleLinear()
.domain([0, 0.4])
.range([h - padding, padding])

function mycanvas() {
var svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h)
svg.append('rect')
.attr('width', '100%')
.attr('height', '100%')
.attr('fill', 'blue')
// Define the axis
var xAxis = d3.axisBottom().scale(xScale).ticks(9)
var yAxis = d3.axisLeft().scale(yScale).ticks(9)
// Create the axis
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (h - padding) + ')')
.call(xAxis)
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(' + padding + ',0)')
.call(yAxis)

svg.selectAll('line')
.data(dataset)
.enter()
.append('line')
.attr('x1', function(d) {
return xScale(d[0])
})
.attr('y1', function(d) {
return yScale(d[1])
})
.attr('x2', function(d) {
return xScale(d[1])
})
.attr('y2', function(d) {
return yScale(d[0])
})
.attr('stroke', 'white')
}

function main() {
mycanvas()
}

window.onload = main

<script src="https://d3js.org/d3.v4.min.js"></script>





The main problem is when i try to plot with svg line i don't know how to fix the right way to call and apply dataset array with x1,y1,x2,y2

Answer Source

You could use d3.line to produce a path from dataset:

var line = d3.line()
             .x(function(d) { return xScale(d[0]);})
             .y(function(d) { return yScale(d[1]);});

svg.append("path")
   .attr("d", line(dataset))
   .attr("stroke", "white")
   .attr("fill", "none");

Demo: https://jsfiddle.net/LukaszWiktor/kkxe5sbc/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download