building d3 force directed graph using dynamic json data - json

my current D3 with static json looks like
var graph = {
"nodes":[
{"name":"User Login","group":1},
{"name":"Appointments","group":1},
{"name":"Store Visit","group":1},
{"name":"Visit History","group":1},
{"name":"Resume Store Visit","group":1}
],
"links":[
{"source":1,"target":0,"value":1},
{"source":2,"target":0,"value":8},
{"source":3,"target":0,"value":10},
{"source":3,"target":2,"value":6},
{"source":4,"target":0,"value":1}
]
};
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(300)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
force
.nodes(graph.nodes)
.links(graph.links)
.start();
svg.append("svg:defs").selectAll("marker")
.data(["end"]) // Different link/path types can be defined here
.enter().append("svg:marker") // This section adds in the arrows
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.attr("marker-end", "url(#end)")
.style("stroke-width", function(d) {
return Math.sqrt(d.value);
});
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter()
.append("g")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.call(force.drag);
node.append("rect")
.attr("class", "node")
.attr("width", 100)
.attr("height", 35)
.style("fill", function(d) {
return color(d.group);
})
.style("stroke", "black")
.style("stroke-width", "1px");
node.append("text")
.text(function(d) {
return d.name + '(' + d.group + ')';
})
.style("font-size", "12px")
.attr("dy", "1em");
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("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
</script>
I want to move the static data to move to a js file and fetch it using my rest service like i am doing for other morris charts where the script looks like
$.ajax({ url: 'http://127.0.0.1:7101/MUDRESTService/rest/v1/meventsbydaybar?onlyData=true&limit=99',
type: 'get',
dataType: 'json',
success: function(output) {
var ddata = JSON.stringify(output.items);
var arr = JSON.parse(ddata);
bar.setData(arr);
}
});
Please advise how to use my above rest service as a source for the d3 graph

using
var data; // a global
d3.json("http://127.0.0.1:7101/MUDRESTService/rest/v1/mudstats?onlyData=true", function(error, json) {
data = json;
});
worked for me

Related

D3 Multi Series Line Chart

I am trying to create a D3 line chart. I have copied the code from the block builder and replaced with my data. Although the code is working but its not showing the labels when i hover the line.
I want to basically get the label details when I hover over the line.
Original Block https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91
Regards,
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 12px Helvetica;
}
.axis line {
fill: red;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 3px;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 50, right: 50, bottom: 30, left: 80},
width = 630 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var cities = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {
date: d.Year,
temperature: +d[name]
};
})
};
});
var xAxis = d3.svg.axis()
.scale(x)
.ticks(10)
.innerTickSize(2)
.outerTickSize(0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.tickFormat(function(d) { return d ;})
.ticks(10)
.innerTickSize(2.5)
.outerTickSize(0)
.orient("left");
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.price); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("https://gist.githubusercontent.com/vaibhavjaitly/f1339c2bc02857afdf65b8d572dc31e5/raw/72ad1af2eacc86575649ae015b433aacb37f3854/US.and.SF.Crimerate.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Year"; }));
data.forEach(function(d) {
d.date = parseDate(d.Year);
});
var companies = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, price: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(companies, function(c) { return d3.min(c.values, function(v) { return v.price; }); }),
d3.max(companies, function(c) { return d3.max(c.values, function(v) { return v.price; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Crime Rate per 10,000");
svg.append("line")
.attr(
{
"class":"horizontalGrid",
"x1" : 0,
"x2" : width,
"y1" : y(0),
"y2" : y(0),
"fill" : "none",
"shape-rendering" : "crispEdges",
"stroke" : "black",
"stroke-width" : "1px",
"stroke-dasharray": ("3, 3")
});
var company = svg.selectAll(".company")
.data(companies)
.enter().append("g")
.attr("class", "company");
var path = svg.selectAll(".company").append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name)
});
var totalLength = [path[0][0].getTotalLength(), path[0][1].getTotalLength()];
console.log(totalLength);
d3.select(path[0][0])
.attr("stroke-dasharray", totalLength[0] + " " + totalLength[0] )
.attr("stroke-dashoffset", totalLength[0])
.transition()
.duration(15000)
.ease("linear")
.attr("stroke-dashoffset", 0);
d3.select(path[0][1])
.attr("stroke-dasharray", totalLength[1] + " " + totalLength[1] )
.attr("stroke-dashoffset", totalLength[1])
.transition()
.duration(15000)
.ease("linear")
.attr("stroke-dashoffset", 0);
});
var mouseG = svg.append("g")
.attr("class", "mouse-over-effects");
mouseG.append("path") // this is the black vertical line to follow mouse
.attr("class", "mouse-line")
.style("stroke", "black")
.style("stroke-width", "1px")
.style("opacity", "0");
var lines = document.getElementsByClassName('line');
var mousePerLine = mouseG.selectAll('.mouse-per-line')
.data(cities)
.enter()
.append("g")
.attr("class", "mouse-per-line");
mousePerLine.append("circle")
.attr("r", 7)
.style("stroke", function(d) {
return color(d.Year);
})
.style("fill", "none")
.style("stroke-width", "1px")
.style("opacity", "0");
mousePerLine.append("text")
.attr("transform", "translate(10,3)");
mouseG.append('svg:rect') // append a rect to catch mouse movements on canvas
.attr('width', width) // can't catch mouse events on a g element
.attr('height', height)
.attr('fill', 'none')
.attr('pointer-events', 'all')
.on('mouseout', function() { // on mouse out hide line, circles and text
d3.select(".mouse-line")
.style("opacity", "0");
d3.selectAll(".mouse-per-line circle")
.style("opacity", "0");
d3.selectAll(".mouse-per-line text")
.style("opacity", "0");
})
.on('mouseover', function() { // on mouse in show line, circles and text
d3.select(".mouse-line")
.style("opacity", "1");
d3.selectAll(".mouse-per-line circle")
.style("opacity", "1");
d3.selectAll(".mouse-per-line text")
.style("opacity", "1");
})
.on('mousemove', function() { // mouse moving over canvas
var mouse = d3.mouse(this);
d3.select(".mouse-line")
.attr("d", function() {
var d = "M" + mouse[0] + "," + height;
d += " " + mouse[0] + "," + 0;
return d;
});
d3.selectAll(".mouse-per-line")
.attr("transform", function(d, i) {
console.log(width/mouse[0])
var xDate = x.invert(mouse[0]),
bisect = d3.bisector(function(d) { return d.Year; }).right;
idx = bisect(d.values, xYear);
var beginning = 0,
end = lines[i].getTotalLength(),
target = null;
while (true){
target = Math.floor((beginning + end) / 2);
pos = lines[i].getPointAtLength(target);
if ((target === end || target === beginning) && pos.x !== mouse[0]) {
break;
}
if (pos.x > mouse[0]) end = target;
else if (pos.x < mouse[0]) beginning = target;
else break; //position found
}
d3.select(this).select('text')
.text(y.invert(pos.y).toFixed(2));
return "translate(" + mouse[0] + "," + pos.y +")";
});
});
</script>
Minor change:
The "date" column being used in the code is based on the reference data. In your case, it should be changed to "Year".
Changing:
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
to
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Year"; }));
and
d.date = parseDate(d.date);
to
d.date = parseDate(d.Year);
Here's a new block:
https://bl.ocks.org/shashank2104/8d4aa05b7cf14d15099e0a0c47476f0e/d0c76a98426d7524b97f5c815b05c3d91d5b6dd0
Hope this helps.

populating the JSON data from spring mvc to d3 chart using request body

I'm tyring to poplulate the data from the server as json into d3 to generate chart.
In server side I generated the JSON object using spring as below, by just populating the data in hashmap and sending the responce through spring responce body.
#RequestMapping("/greeting1")
#ResponseBody
public LinkedHashMap<String, String> greeting1(#RequestParam(value = "name", required = false) String name,
Model model) {
LinkedHashMap<String, String> values = data.populateData();
model.addAttribute("name", values);
return values;
}
In client side I'm populating the data to a div and trying to inject into d3 as below (but dosen't work).
case 1:
var test_data=d3.select("body").selectAll("test_data");
data=test_data.html;
x.domain(data.map(function(d) { return d.x; }));
y.domain(data.map(function(d) { return d.y; }));
The above code is requiring JSON as in the following format.
case 2:
var data = [{x:0,y:0.5},{x:0.1,y:0.8},{x:0.2,y:1.1},{x:1.3,y:1.5},{x:0.4,y:2.5},{x:0.5,y:3.4},{x:0.6,y:4.3}];
x.domain(data.map(function(d) { return d.x; }));
y.domain(data.map(function(d) { return d.y; }));
How shall I generate the JSON in the format specified from the server side ( as in case 2) ?
How shall i capture the div test_data in d3 ?
complete js code for d3 as below.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="utf-8"></meta>
<style>
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke-width: 1.5px;
}
.dot {
fill: #fff;
stroke: #000;
}
</style>
<script src="./d3.js"></script>
<script src="./jquery.js"></script>
<script src="./data.tsv"></script>
<script>
$(document).ready(function(){
sendAjax();
});
function sendAjax() {
$.ajax({
url: "/greeting1",
type: 'GET',
/* dataType: 'json',
data: "{\"name\":\"hmkcode\",\"id\":2}",
contentType: 'application/json',
mimeType: 'application/json',*/
success: function(data) {
//alert(data);
$('#test_data').html(data);
//alert($('#test_data').html);
callChart();
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
<div id="test"></div>
<div id="test_data"></div>
<script>
function callChart()
{
var margin = {top: 40, right: 40, bottom: 40, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var z = d3.scale.linear()
.domain([2 / 3, 1]) // D3 3.x tension is buggy!
.range(["brown", "steelblue"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.tsv("data.tsv", type, function(error, data) {
// if (error) throw error;
//var test_data=d3.select("body").selectAll("test_data");
//data=test_data.html;
var data = [{x:0,y:0.5},{x:0.1,y:0.8},{x:0.2,y:1.1},{x:1.3,y:1.5},{x:0.4,y:2.5},{x:0.5,y:3.4},{x:0.6,y:4.3}];
x.domain(data.map(function(d) { return d.x; }));
y.domain(data.map(function(d) { return d.y; }));
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
svg.selectAll(".line")
.data(z.ticks(6))
.enter().append("path")
.attr("class", "line")
.attr("d", function(d) { return line.tension(d)(data); })
.style("stroke", z);
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("r", 3.5);
//});
function type(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
}
</script>
</body>
</html>
My problem is solved by using gson for constructing the Json and the solution provided by #Gerardo Furtado for fetching the div through d3.
#RequestMapping("/greeting")
public String greeting(#RequestParam(value = "name", required = false, defaultValue = "World") String name,
Model model) {
LinkedList<Data.Temp> values = data.populateData();
Gson gson = new Gson();
String output=gson.toJson(values);
model.addAttribute("name",output );
return "greeting";
}
function callChart()
{
var margin = {top: 40, right: 40, bottom: 40, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var z = d3.scale.linear()
.domain([2 / 3, 1]) // D3 3.x tension is buggy!
.range(["brown", "steelblue"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.tsv("data.tsv", type, function(error, data) {
// if (error) throw error;
//var test_data=d3.select("body").selectAll("test_data");
//data=test_data.html;
var test_data = d3.select("#test_data");
var data = JSON.parse(test_data.text());
x.domain(data.map(function(d) { return d.x; }));
y.domain(data.map(function(d) { return d.y; }));
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
svg.selectAll(".line")
.data(z.ticks(6))
.enter().append("path")
.attr("class", "line")
.attr("d", function(d) { return line.tension(d)(data); })
.style("stroke", z);
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("r", 3.5);
//});
function type(d) {
d.x = +d.x;
d.y = +d.y;
return d;
}
}

Unable to create bar chart from d3 using URL

I am trying to create bar chart from json file which is a URL but i am unable to do so please help me, as i am new to d3. The code is here please tell me where i am making mistake.
var width = 960,
height = 500;
var y = d3.scale.linear().range([height, 0]);
var chart = d3.select("#chart")
.append("svg")
.attr("width", width)
.attr("height", height);
generateChart();
function generateChart() {
d3.json('http://dataserver.org:8009/topic/domain/cancer',
function(error, data) {
y.domain([0, d3.max(data, function(d) {
return d.occurrence
})]);
var barWidth = width / data.length; //width of each bar
var bar = chart.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) {
return "translate(" + i * barWidth + ", 0)";
});
bar.append("rect")
.attr("y", function(d) {
return y(d.occurrence);
})
.attr("height", function(d) {
return height - y(d.occurrence);
})
.attr("width", barWidth - 1);
bar.append("text")
.attr("x", barWidth / 2)
.attr("y", function(d) {
return y(d.occurrence) - 10;
})
.attr("dy", ".75em")
.text(function(d) {
return d.authorName;
});
});
};
It is not a problem of cross domain as I checked your API. Assuming that you are fetching d3.js from CDN, I am suggesting a change. Your chart will depend on "institute" as it is containing all the required values for chart. So I changed it as per structure your API's response.
**in some case data was coming as "undefined" so I am fetching d3.js from CDN
Here is whole modified file:-
function generateChart() {
d3.json('http://srvgal78.deri.ie:8009/topic/domain/cancer',
function(error, data) {
data = data.institute;
y.domain([0, d3.max(data, function(d) {
return d.occurrence
})]);
var barWidth = width / data.length; //width of each bar
var bar = chart.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d, i) {
return "translate(" + i * barWidth + ", 0)";
});
bar.append("rect")
.attr("y", function(d) {
return y(d.occurrence);
})
.attr("height", function(d) {
return height - y(d.occurrence);
})
.attr("width", barWidth - 1);
bar.append("text")
.attr("x", barWidth / 2)
.attr("y", function(d) {
return y(d.occurrence) - 10;
})
.attr("dy", ".75em")
.text(function(d) {
return d.authorName;
});
});
};

Create dynamic Word Cloud using d3.js

I am using the following example as base and want to make it dynamic word cloud
https://github.com/jasondavies/d3-cloud
The data is added to the array but my word-cloud is not reflecting the newly added word(s):
<script>
var fill = d3.scale.category20();
var data = [{word:"Hello",weight:20},{word:"World",weight:10},{word:"Normally",weight:25},{word:"You",weight:15},{word:"Want",weight:30},{word:"More",weight:12},{word:"Words",weight:8},{word:"But",weight:18},{word:"Who",weight:22},{word:"Cares",weight:27}];
d3.layout.cloud().size([500, 500])
.words(data.map(function(d) {
return {text: d.word, size: d.weight};
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
function drawUpdate(words){
//alert(JSON.stringify(words)); //shows me the added data
d3.select("body").selectAll("text")
.data(words.map(function(d) {
return {text: d.word, size: d.weight};
}))
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.text(function(d) { return d.text; });
}
setInterval(function () {
var d_new = data;
d_new.push({word: "Mappy",weight:35});
drawUpdate(d_new);
}, 1500);
</script>
Also, it refreshed the first time, but without the new word added. Could someone please rectify or point out what am I doing wrong in this.
Thanks
Thanks to Larks I was able to get it done. Here I am sharing the code if anyone else faces a similar issue, I hope it can help
<script>
var fill = d3.scale.category20();
var data = [{word:"Hello",weight:20},{word:"World",weight:10},{word:"Normally",weight:25},{word:"You",weight:15},{word:"Want",weight:30},{word:"More",weight:12},{word:"Words",weight:8},{word:"But",weight:18},{word:"Who",weight:22},{word:"Cares",weight:27}];
d3.layout.cloud().size([500, 500])
.words(data.map(function(d) {
return {text: d.word, size: d.weight};
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
function drawUpdate(words){
d3.layout.cloud().size([500, 500])
.words(words)
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.start();
d3.select("svg")
.selectAll("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words).enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
setInterval(function () {
var d_new = data;
d_new.push({word:randomWord(),weight:randomWeight()});
drawUpdate(d_new.map(function(d) {
return {text: d.word, size: d.weight};
}));
}, 1500);
function randomWord() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function randomWeight(){
var r = Math.round(Math.random() * 100);
return r;
}
</script>

set date without time in D3 js

I am working on D3 js.
I am a Lerner and trying to render the multi line graph but i am not able to set proper date format.i wanted to remove 12 PM .example like April 12 PM Wed 02
below is my code
var margin = { top: 40, right: 40, bottom: 35, left: 85 },
width = 800 - margin.left - margin.right,
height = 350 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y%m%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.request); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.tsv("data.tsv", function (error, data) {
color.domain(d3.keys(data.ListWeekly[0]).filter(function (key) { return key !== "date"; }));
data.ListWeekly.forEach(function (d) {
d.date = parseDate(d.date);
});
var cities = color.domain().map(function (name) {
return {
name: name,
values: data.ListWeekly.map(function (d) {
return { date: d.date, request: +d[name] };
})
};
});
x.domain(d3.extent(data.ListWeekly, function (d) { return d.date; }));
y.domain([
d3.min(cities, function (c) { return d3.min(c.values, function (v) { return v.request; }); }),
d3.max(cities, function (c) { return d3.max(c.values, function (v) { return v.request; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Request");
var city = svg.selectAll(".city")
.data(cities)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line")
.attr("d", function (d) { return line(d.values); })
.style("stroke", function (d) { return color(d.name); });
city.append("text")
.datum(function (d) { return { name: d.name, value: d.values[d.values.length - 1] }; })
.attr("transform", function (d) { return "translate(" + x(d.value.date) + "," + y(d.value.request) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function (d) { return d.name; });
//});
my json data
var List = new List<object>();
List.Add(new { date = "20140401", weekday = "163", weekend = "263" });
List.Add(new { date = "20140402", weekday = "153", weekend = "253" });
List.Add(new { date = "20140403", weekday = "133", weekend = "233" });
List.Add(new { date = "20140404", weekday = "167", weekend = "373" });
List.Add(new { date = "20140405", weekday = "123", weekend = "183" });
List.Add(new { date = "20140406", weekday = "178", weekend = "123" });
List.Add(new { date = "20140407", weekday = "32", weekend = "223" });
return Json(new { ListWeekly = List });
You can set the time format using the d3.time.format helper and set the format of the tick labels of the axis using the axis tickFormat method. To have the dates formatted as 2014-04-30, you can use the following code:
// Create a time format generator
var dateFmt = d3.time.format('%Y-%m-%d'); // 2014-04-30
// The dateFmt function returns a string with the formatted date
console.log(dateFmt(new Date('2014/04/04')); // 2014-04-04
// Set the tick format for the xAxis
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(function(d) { return dateFmt(d.date); });