set date without time in D3 js - json

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); });

Related

D3 svg chart can't display in IE

I'm building a website which contains d3 svg to display the bar chart. It can display in Chrome, Firefox, Edge, Safari, but it is not working in IE. I have tried to use canvas method, but it is not working. Then I tried set viewbox for svg, but it is not working as well. Could anyone help me solve this problem?
Here's my d3.js and html code
function homeStats() {
var jsonobj = document.getElementById('stats-data').value;
var data = JSON.parse(jsonobj);
var parentDiv = document.getElementById("home-stats");
function drawbar() {
var margin = { top: 40, right: 20, bottom: 100, left: 40 };
var width = parentDiv.clientWidth - margin.left - margin.right;
var height = parentDiv.clientHeight - margin.top - margin.bottom;
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
return "<span style='color:white'>" + d.value + "</span>";
})
d3.selectAll('#home-stats-svg').remove()
var svg = d3.select("#home-stats").append("svg").attr("id", "home-stats-svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.call(tip);
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .65);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#f79944", "#20b5e1"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
var columnNames = d3.keys(data[0]).filter(function (key) { return key !== "Year"; });
data.forEach(function (d) {
d.subGroups = columnNames.map(function (name) { return { name: name, value: +d[name] }; });
});
x0.domain(data.map(function (d) { return d.Year; }));
x1.domain(columnNames).rangeRoundBands([0, 30]);
y.domain([0, d3.max(data, function (d) { return d3.max(d.subGroups, function (d) { return d.value; }); })]);
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");
const rx = 5;
const ry = 5;
var Year = svg.selectAll(".Year")
.data(data)
.enter().append("g")
.attr("class", "Year")
.attr("transform", function (d) { return "translate(" + x0(d.Year) + ",0)"; });
Year.selectAll("rect")
.data(function (d) { return d.subGroups; })
.enter().append("path")
.style("fill", function (d) { return color(d.name); })
.attr("d", item => `
M${x1(item.name)},${y(item.value) + ry}
a${rx},${ry} 0 0 1 ${rx},${-ry}
h${10 - 2 * rx}
a${rx},${ry} 0 0 1 ${rx},${ry}
v${height - y(item.value) - ry}
h${-(10)}Z
`)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
var legend = svg.selectAll(".legend")
.data(columnNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 5)
.attr("width", "1vw")
.attr("height", "2vh")
.style("fill", color);
legend.append("text")
.attr("x", width - 7)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
}
drawbar();
}
Html
<div id="home-stats" style="height:50vh; width:45vw">
<input type="hidden" id="stats-data" value=#ViewBag.deaths_json />
<svg id="home-stats-svg" viewBox="0 0 100 100"></svg>
</div>
Since the arrow function expression doesn't support IE browser, we could use babeljs.io to convert this function to ES5 format.

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;
}
}

building d3 force directed graph using dynamic json data

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

D3 update line graph

I created a line graph using a csv file and now I am trying to update this graph using new data from the same csv. However when I open the file in firefox I am getting an error: ReferenceError: updateData is not defined.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="d3/d3.min.js"></script>
</head>
<body>
<div id="option">
<input name="updateButton"
type="button"
value="Update"
onclick="updateData()" />
</div>
<script type="text/javascript">
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 150},
width = 1000 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.tickFormat(d3.format(".0f"))
.orient("bottom");
var yAxis = d3.svg.axis().scale(y)
.orient("left")
.ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.Year); })
.y(function(d) { return y(d.AttendancePerG); });
// Adds the svg canvas
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 + ")");
// Get the data
d3.csv("piratesAttendance.csv", function(error, data) {
data.forEach(function(d) {
d.Year = +d.Year;
d.AttendancePerG = +d.AttendancePerG;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.Year; }));
y.domain([0, d3.max(data, function(d) { return d.AttendancePerG; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data))
.attr("stroke", "black")
.attr("stroke-width",2)
.attr("fill","none");
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function updateData() {
// Get the data again
d3.tsv("pittsburghAttendance", function(error, data) {
data.forEach(function(d) {
d.Year = +d.Year;
d.Attendance = +d.Attendance;
});
// Scale the range of the data again
x.domain(d3.extent(data, function(d) { return d.Year; }));
y.domain([0, d3.max(data, function(d) { return d.Attendance; })]);
// Select the section we want to apply our changes to
var svg = d3.select("body").transition();
// Make the changes
svg.select(".line") // change the line
.duration(750)
.attr("class", "line")
.attr("d", valueline(data));
svg.select(".x.axis") // change the x axis
.duration(750)
.call(xAxis);
svg.select(".y.axis") // change the y axis
.duration(750)
.call(yAxis);
});
}
});
</script>
</body>
</html>
Your function updateData is defined in a callback, so it will not be in the "global" scope of your page, hence you cannot invoke it from the HTML.
Try to simply move its declaration to the beginning (or end) of your <script> tag.
Oh and also your usage of d3.csv seems incorrect.