I was hoping somebody could help, I'm completely new to javascript but have been learning it in order to start producing interactive outputs in D3.
So I've started with the basics and produced line graphs etc, now I want to add an interactive element.
So I have a line graph, a slider and a function, the question is how do I link these up? playing with some online examples I understand how I can get the slider to update attributes of objects such as text, but I want it to update parameters in a loop to perform a calculation, which then runs and gives the line graph output.
My code is as follows and I've annotated the loop which I want to update:
<!DOCTYPE html>
<style type="text/css">
path {
stroke-width: 2;
fill: none;
}
line {
stroke: black;
}
text {
font-family: Arial;
font-size: 9pt;
}
</style>
<body>
<p>
<label for="repRate"
style="display: inline-block; width: 240px; text-align: right">
R = <span id="repRate-value">…</span>
</label>
<input type="range" min="0.0" max="1.0" step="0.01" id="repRate">
</p>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
d3.select("#repRate").on("input", function() {
update(+this.value);
});
update(0.1);
function update(repRate) {
// adjust slider text
d3.select("#repRate-value").text(repRate);
d3.select("#repRate").property("value", repRate);
}
//This is the function I want to update when the slider moves, I want the parameter R to update
//with the slider value, then loop through and produce a new graph
function parHost (R){
var i = 0;
var result = [];
do {
//I want to be able to keep it as a loop or similar, so that I can add more complex
//equations into it, but for now I've kept it simple
Nt1 = R*i
result.push(Nt1++) ;
Nt = Nt1
i++;
}
while (i < 50);
return result};
var data = parHost(0.5),
w = 900,
h = 200,
marginY = 50,
marginX = 20,
y = d3.scale.linear().domain([0, d3.max(data)]).range([0 + marginX, h - marginX]),
x = d3.scale.linear().domain([0, data.length]).range([0 + marginY, w - marginY])
var vis = d3.select("body")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
var g = vis.append("svg:g")
.attr("transform", "translate(0, 200)");
var line = d3.svg.line()
.x(function(d,i) { return x(i); })
.y(function(d) { return -1 * y(d); })
g.append("svg:path").attr("d", line(data)).attr('stroke', 'blue');
g.append("svg:line")
.attr("x1", x(0))
.attr("y1", -1 * y(0))
.attr("x2", x(w))
.attr("y2", -1 * y(0))
g.append("svg:line")
.attr("x1", x(0))
.attr("y1", -1 * y(0))
.attr("x2", x(0))
.attr("y2", -1 * y(d3.max(data)))
g.selectAll(".xLabel")
.data(x.ticks(5))
.enter().append("svg:text")
.attr("class", "xLabel")
.text(String)
.attr("x", function(d) { return x(d) })
.attr("y", 0)
.attr("text-anchor", "middle")
g.selectAll(".yLabel")
.data(y.ticks(4))
.enter().append("svg:text")
.attr("class", "yLabel")
.text(String)
.attr("x", 0)
.attr("y", function(d) { return -1 * y(d) })
.attr("text-anchor", "right")
.attr("dy", 4)
g.selectAll(".xTicks")
.data(x.ticks(5))
.enter().append("svg:line")
.attr("class", "xTicks")
.attr("x1", function(d) { return x(d); })
.attr("y1", -1 * y(0))
.attr("x2", function(d) { return x(d); })
.attr("y2", -1 * y(-0.3))
g.selectAll(".yTicks")
.data(y.ticks(4))
.enter().append("svg:line")
.attr("class", "yTicks")
.attr("y1", function(d) { return -1 * y(d); })
.attr("x1", x(-0.3))
.attr("y2", function(d) { return -1 * y(d); })
.attr("x2", x(0))
</script>
</body>
Any help with this would be much appreciated.
On each slider input event you have to update the parts of the chart (e.g. line, axisTicks, etc.) which depend on your data. You could e.g. extend your update function like this:
function update(repRate) {
// adjust slider text
d3.select("#repRate-value").text(repRate);
d3.select("#repRate").property("value", repRate);
// Generate new Data depending on slider value
var newData = parHost(repRate);
// Update the chart
drawChart(newData);
}
where the drawChart(newData) could look like this:
function drawChart(newData) {
// Delete the old elements
g.selectAll("*").remove();
g.append("svg:path").attr("d", line(newData)).attr('stroke', 'blue');
...
}
Another method is to declare data depending elements as variables and just change their attribute on an update (which i would recommend):
...
var dataLine = g.append("svg:path");
...
function drawChart(newData) {
path.attr("d", line(newData)).attr('stroke', 'blue');
}
Here is an example plunker.
Check out also this example.
Related
I have a button which I have created using the Div element in my html file. This button is supposed to be linked to my d3.js file via the grid lines. In my JS file I have created supposedly user friendly horizontal and vertical grid lines which are supposed to guide the user position other visualization on the page and then be turned off after its used.
Problem is I'm new to JavaScript and D3 in general and I can't seem to figure out how to link my div buttons to my SVG created grid lines to create the hide/show effect even after sternly scrapping through stack over flow and google. I have tried different variations and ideas with no success.
Code for my button
<body>
<div id="option">
<input name="updateButton"
type="button"
value="On/Off"
onclick="updateGrid()"
/>
</div>
</body>
code for my grid lines
var width = 1500,
height = 800,
colors = d3.scale.category20();
var svg = d3.select('body')
.append('svg')
.attr('oncontextmenu', 'return false;')
.attr('width', width)
.attr('height', height);
//vertical lines
Ver= svg.selectAll(".vline").data(d3.range(26)).enter()
.append("line")
.attr("x1", function (d) {
return d * 80;
})
.attr("x2", function (d) {
return d * 80;
})
.attr("y1", function (d) {
return 0;
})
.attr("y2", function (d) {
return 800;
})
.style("stroke", "#eee");
// horizontal lines
hor= svg.selectAll(".vline").data(d3.range(26)).enter()
.append("line")
.attr("y1", function (d) {
return d * 60;
})
.attr("y2", function (d) {
return d * 60;
})
.attr("x1", function (d) {
return 0;
})
.attr("x2", function (d) {
return 1500;
})
.style("stroke", "#eee");
There are different ways to achieve what you want.
My advice here is, since you're already using D3, don't call a function inline. Instead of that, use D3 itself to listen to the button click:
var toggle = true;
d3.select("input").on("click", function() {
d3.selectAll("line").style("opacity", +(toggle = !toggle))
})
Here I'm simply toggling the opacity between 0 and 1. In case you don't know (since you said you're new to JavaScript and D3), +true is 1 and +false is 0 (that's why I'm using the unary plus), and !toggle inverts the boolean.
Here is a demo, using your code with some minor changes:
var width = 1500,
height = 800,
colors = d3.scale.category20();
var svg = d3.select('body')
.append('svg')
.attr('oncontextmenu', 'return false;')
.attr('width', width)
.attr('height', height);
//vertical lines
var ver = svg.selectAll(null).data(d3.range(26)).enter()
.append("line")
.attr("x1", function(d) {
return d * 80;
})
.attr("x2", function(d) {
return d * 80;
})
.attr("y1", function(d) {
return 0;
})
.attr("y2", function(d) {
return 800;
})
.style("stroke", "#666")
.style("shape-rendering", "crispEdges");
// horizontal lines
var hor = svg.selectAll(null).data(d3.range(26)).enter()
.append("line")
.attr("y1", function(d) {
return d * 60;
})
.attr("y2", function(d) {
return d * 60;
})
.attr("x1", function(d) {
return 0;
})
.attr("x2", function(d) {
return 1500;
})
.style("stroke", "#666")
.style("shape-rendering", "crispEdges");
var toggle = true;
d3.select("input").on("click", function() {
d3.selectAll("line").style("opacity", +(toggle = !toggle))
})
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="option">
<input name="updateButton" type="button" value="On/Off" />
</div>
Hope my code will help:
// I add a div container instead of the <body> tag
var svg = d3.select("#container")
.append('svg')
.attr('oncontextmenu', 'return false;')
.attr('width', 1500)
.attr('height', 800)
.style("border", "1px solid #ccc")
// initial
redraw("horizontal");
// I prefer 'd3.select("#option input").on("click", func)' style
function updateGrid(event){
var btu = d3.select(event.target);
if(btu.attr("value") === "On"){
btu.attr("value", "Off");
redraw("vertical");
}else{
btu.attr("value", "On");
redraw("horizontal");
}
}
function redraw(type){
var data = d3.range(26), update, enter;
// there are three stage of binding data: update, enter and exit.
// But I just need to define two stage in your case.
update = svg
.selectAll("line")
// all line to be marked with a specific value
.data(data, function(d){ return d; });
enter = update
.enter()
.append("line")
.attr({
x1: 0, x2: 0,
y1: 0, y2: 0,
stroke: "black",
"stroke-width": 1
});
if(type === "horizontal"){
update
.transition()
.duration(1000)
.attr({
x1: 0, x2: 1500,
y1: function(d){ return d * 60; },
y2: function(d){ return d * 60; }
})
}else{
update
.transition()
.duration(1000)
.attr({
x1: function(d){ return d * 60; },
x2: function(d){ return d * 60; },
y1: 0, y2: 800
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="option">
<input name="updateButton" type="button" value="On" onclick="updateGrid(event)" />
</div>
<div id="container"></div>
I'm having trouble getting a transition to repeat, for a series of elements, in this case a set of three lines. The animation runs just fine once, but when it is repeated (with the same data), all three lines merge into a single line (the last array in data). What am I doing wrong?
(function() {
var w = 100, h = 100
var div = d3.select('#sketches').append('div')
var svg = div.append("svg")
.attr("width", w)
.attr("height", h)
var x = 0, y = 55
var data = [
[x, y, x+20, y-40],
[x+10, y, x+30, y-40],
[x+20, y, x+40, y-40]
];
(function lines() {
svg.selectAll('line')
.data(data).enter().append('line')
.attr("stroke", "black")
.attr('x1', function(d) {return d[0]})
.attr('y1', function(d) {return d[1]})
.attr('x2', function(d) {return d[2]})
.attr('y2', function(d) {return d[3]})
.transition()
.duration(3000)
.ease('linear')
.attr('x1', function(d) {return d[0] + 60})
.attr('y1', function(d) {return d[1]})
.attr('x2', function(d) {return d[2] + 60})
.attr('y2', function(d) {return d[3]})
.each('end', function(d) {
d3.select(this).remove()
lines()
})
})()
})()
body {
padding: 1rem;
}
svg {
background-color: silver;
stroke: black;
stroke-width: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="sketches"></div>
The issue is the each function will initiate for each line you have. So actually what you are doing is calling lines() three times every time. Why it's yieling the output of one line I'm not entirely sure (still looking into it) but for some reason, it seems like data defaults to the last array so its only setting the drawing to be based on data[3].
To fix it, you want to make sure lines() only gets called after it has finished going through removing all the lines so it only runs once. I'm pretty sure there is better way (i.e. a promise of some kind so after all of each has ran, it'll run a function, but what you can do is set a count and then just run lines() every N times where N is the number of lines you want removed. Because you go through array data and append a line for each index, N is data.length.
(I'm gonna see if there's a cleaner way to do this and I'll edit my answer if I find a way but hopefully this helps you understand the issue at the very least)
(function() {
var w = 100, h = 100
var div = d3.select('#sketches').append('div')
var svg = div.append("svg")
.attr("width", w)
.attr("height", h)
var x = 0, y = 55
var data = [
[x, y, x+20, y-40],
[x+10, y, x+30, y-40],
[x+20, y, x+40, y-40]
];
var count = 0;
(function lines() {
svg.selectAll('line')
.data(data).enter().append('line')
.attr("stroke", "black")
.attr('x1', function(d) {return d[0]})
.attr('y1', function(d) {return d[1]})
.attr('x2', function(d) {return d[2]})
.attr('y2', function(d) {return d[3]})
.transition()
.duration(3000)
.ease('linear')
.attr('x1', function(d) {return d[0] + 60})
.attr('y1', function(d) {return d[1]})
.attr('x2', function(d) {return d[2] + 60})
.attr('y2', function(d) {return d[3]})
.each('end', function(d) {
d3.select(this).remove()
count++;
if (count == data.length) {
count = 0;
lines();
}
})
})()
})()
body {
padding: 1rem;
}
svg {
background-color: silver;
stroke: black;
stroke-width: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="sketches"></div>
I've added a new peice of javascript to an old script I had to add a highlighting functionality to a force network layout. I get the information for the diagram from generated json in a rails app. The original code I've been using is here:
var width = 960,
height = 960;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-100)
.linkDistance(530)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var endpoint = window.location.href+".json"
d3.json(endpoint, function(graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("marker-end", "url(#suit)");
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.style("fill", function(d) { return color(d.group); })
.call(force.drag)
.on('dblclick', connectedNodes);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
svg.append("defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 25)
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5 L10,0 L0, -5")
.style("stroke", "#4679BD")
.style("opacity", "0.6");
//APPENDED CODE ADDED HERE
//Toggle stores whether the highlighting is on
var toggle = 0;
//Create an array logging what is connected to what
var linkedByIndex = {};
for (i = 0; i < graph.nodes.length; i++) {
linkedByIndex[i + "," + i] = 1;
};
graph.links.forEach(function (d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
//This function looks up whether a pair are neighbours
function neighboring(a, b) {
return linkedByIndex[a.index + "," + b.index];
}
function connectedNodes() {
if (toggle == 0) {
//Reduce the opacity of all but the neighbouring nodes
d = d3.select(this).node().__data__;
node.style("opacity", function (o) {
return neighboring(d, o) | neighboring(o, d) ? 1 : 0.1;
});
link.style("opacity", function (o) {
return d.index==o.source.index | d.index==o.target.index ? 1 : 0.1;
});
//Reduce the op
toggle = 1;
} else {
//Put them back to opacity=1
node.style("opacity", 1);
link.style("opacity", 1);
toggle = 0;
}
}
I then tried to append further code as suggested here and simply added the following to the bottom of the script above where it is marked in capital letters
Could have been so simple.... The script worked but the added functionlity (to add highlights between nodes) didn't. An error message says:
Uncaught ReferenceError: graph is not defined
My susipicion is that it relates to the line
d3.json(endpoint, function(graph) {
and the fact that the subsequent }); is in the wrong place to encompass the new code but I've played with it and I'm not sure how to correct it
UPDATE
I've solved this. The problem was simply that I was declaring graph inside a function and the other functions couldn't access it. The solution is to put the other functions inside the function that delares it which in effect means moving the last
});
from the line
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
to the very last line. Works fine now
The answer is now given in the UPDATE section of the question
I am just starting on D3, so if anyone has any general suggestions on thing I might not be doing correctly/optimally, please let me know :)
I am trying to create a Force Directed graph with the nodes spaced out evenly (or close enough) around the center root node (noted by the larger size).
Here's an example of the layout I'm trying to achieve (I understand it won't be the same every time):
I have the following graph:
var width = $("#theVizness").width(),
height = $("#theVizness").height();
var color = d3.scale.ordinal().range(["#ff0000", "#fff000", "#ff4900"]);
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("#theVizness").append("svg")
.attr("width", width)
.attr("height", height);
var loading = svg.append("text")
.attr("class", "loading")
.attr("x", width / 2)
.attr("y", height / 2)
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text("Loading...");
/*
ForceDirectData.json
{
"nodes":[
{"name":"File1.exe","colorGroup":0},
{"name":"File2.exe","colorGroup":0},
{"name":"File3.exe","colorGroup":0},
{"name":"File4.exe","colorGroup":0},
{"name":"File5.exe","colorGroup":0},
{"name":"File6.exe","colorGroup":0},
{"name":"File7.exe","colorGroup":0},
{"name":"File8.exe","colorGroup":0},
{"name":"File8.exe","colorGroup":0},
{"name":"File9.exe","colorGroup":0}
],
"links":[
{"source":1,"target":0,"value":10},
{"source":2,"target":0,"value":35},
{"source":3,"target":0,"value":50},
{"source":4,"target":0,"value":50},
{"source":5,"target":0,"value":65},
{"source":6,"target":0,"value":65},
{"source":7,"target":0,"value":81},
{"source":8,"target":0,"value":98},
{"source":9,"target":0,"value":100}
]
}
*/
d3.json("https://dl.dropboxusercontent.com/u/5772230/ForceDirectData.json", function (error, json) {
var nodes = json.nodes;
force.nodes(nodes)
.links(json.links)
.linkDistance(function (d) {
return d.value * 1.5;
})
.charge(function(d){
var charge = -500;
if (d.index === 0) charge = 0;
return charge;
})
.friction(0.4);
var link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
var files = svg.selectAll(".file")
.data(json.nodes)
.enter().append("circle")
.attr("class", "file")
.attr("r", 10)
.attr("fill", function (d) {
return color(d.colorGroup);
});
var totalNodes = files[0].length;
files.append("title")
.text(function (d) { return d.name; });
force.start();
for (var i = totalNodes * totalNodes; i > 0; --i) force.tick();
nodes[0].x = width / 2;
nodes[0].y = height / 2;
link.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
files.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("class", function(d){
var classString = "file"
if (d.index === 0) classString += " rootFile";
return classString;
})
.attr("r", function(d){
var radius = 10;
if (d.index === 0) radius = radius * 2;
return radius;
});
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
files.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
loading.remove();
});
JSFiddle
I have already tried getting close to this with the charge() method. I thought giving every node besides the root node a higher charge would accomplish this, but it did not.
What can I do to have the child nodes evenly spaced around the root node?
Yes, force layout is a perfect tool for situations like yours.
You just need to change a little initialization of the layout, like this
force.nodes(nodes)
.links(json.links)
.charge(function(d){
var charge = -500;
if (d.index === 0) charge = 10 * charge;
return charge;
});
and voila
Explanation. I had to remove settings for friction and linkDistance since they affected placement in a bad way. The charge for root node is 10 times larger so that all other nodes are dominantly pushed away from the root. Other nodes also repel each other, and the perfect symmetry is achieved at the end, as a result.
Jsfiddle is here.
I see from your code that you attempted to affect distance from the root node and other nodes by utilizing linkDistance that is dependant on data. However, it might be better (although counter-intuitive) to use linkStrength for that purpose, like this
force.nodes(nodes)
.links(json.links)
.linkStrength(function (d) {
return d.value / 100.0;
})
.charge(function(d){
var charge = -500;
if (d.index === 0) charge = 10 * charge;
return charge;
});
but you need to experiment.
For centering and fixing the root node, you can use this
nodes[0].fixed = true;
nodes[0].x = width / 2;
nodes[0].y = height / 2;
but before initialization of layout, like in this Jsfiddle.
I've just started with trying out the d3 library.
I am trying to create an interactive line chart where people can plot their own points. You can find it over here: http://jsfiddle.net/6FjJ2/
My question is: how can I make sure that plotting can only be done on the x-axis' lines? If you check out my example, you will see it kind of works, but with a lot of cheating. Check out the ok variable... What would be the correct way of achieving this? I have no idea how I can achieve this with a ... so I'm getting a lot of seperate 's.
var data = [2, 3, 4, 3, 4, 5],
w = 1000,
h = 300,
monthsData = [],
months = 18;
for(i = 0; i < months; i++) {
monthsData.push(i);
}
var max = d3.max(monthsData),
x = d3.scale.linear().domain([0, monthsData.length]).range([0, w]),
y = d3.scale.linear().domain([0, max]).range([h, 0]),
pointpos = [];
lvl = [0, 10],
lvly = d3.scale.linear().domain([0, d3.max(lvl)]).range([h, 0]);
svg = d3.select(".chart")
.attr("width", w)
.attr("height", h);
svg.selectAll('path.line')
// Return "data" array which will form the path coordinates
.data([data])
// Add path
.enter().append("svg:path")
.attr("d", d3.svg.line()
.x(function(d, i) { return x(i); })
.y(y));
// Y-axis ticks
ticks = svg.selectAll(".ticky")
// Change number of ticks for more gridlines!
.data(lvly.ticks(10))
.enter().append("svg:g")
.attr("transform", function(d) { return "translate(0, " + (lvly(d)) + ")"; })
.attr("class", "ticky");
ticks.append("svg:line")
.attr("y1", 0)
.attr("y2", 0)
.attr("x1", 0)
.attr("x2", w);
ticks.append("svg:text")
.text( function(d) { return d; })
.attr("text-anchor","end")
.attr("dy", 2)
.attr("dx", -4);
// X-axis ticks
ticks = svg.selectAll(".tickx")
.data(x.ticks(monthsData.length))
.enter().append("svg:g")
.attr("transform", function(d, i) { return "translate(" + (x(i)) + ", 0)"; })
.attr("class", "tickx");
ticks.append("svg:line")
.attr("y1", h)
.attr("y2", 0)
.attr("x1", 0)
.attr("x2", 0);
ticks.append("svg:text")
.text( function(d, i) { return i; })
.attr("y", h)
.attr("dy", 15)
.attr("dx", -2);
// var d = $(".tickx:first line").css({"stroke-width" : "2", opacity : "1"});
var line;
var ok = -55;
svg.on("mousedown", mouseDown)
.on("mouseup", mouseUp);
function mouseDown() {
var m = d3.mouse(this);
line = svg.append("line")
.data(monthsData)
/* .attr("x1", m[0]) */
.attr("x1", function(d, i) { pointpos.push(m[0]); ok += 55; return ok;})
.attr("y1", m[1])
.attr("x2", function(d, i) { return ok + 56; })
/* .attr("x2", function(d, i) {return 300; }) */
.attr("y2", m[1]);
svg.on("mousemove", mouseMove);
var m = d3.mouse(this);
var point = svg.append("circle")
.attr("cx", function(d, i) { return ok; })
.attr("cy", function(d, i) { return m[1]; })
.attr("r", 8);
lvl.push(100);
}
function mouseMove() {
var m = d3.mouse(this);
line.attr("y2", m[1]);
/* .attr("y1", m[0]); */
}
function mouseUp() {
// Change null to mousemove for a graph kinda draw mode
svg.on("mousemove", mouseMove);
}
Excuse my bad code!
Thanks in advance.
It looks like you need:
histogram layout for binning your points.
ordinal scales for restricting their x-axis positions according to the bin
As a sidenote, you can use d3.svg.axis to draw the axis for you.