D3 Multi Series Line Chart - html

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.

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.

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

How increase height dynamically by fixing width of the rect box in d3 js

I'm using d3 js for collapsing tree.
I want to fix the width of the rectangle.
If text size in rectangle box is more than the fixed width of rect box how to increase height of rect box dynamically?
Like below image I want the output.
Here is the code what I'm using
.node {
cursor: pointer;
border-style: solid;
border-width: 2px 10px 4px 20px;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node rect {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A. Some text here Some text here Some text here",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
// ************** Generate the tree diagram *****************
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.source(function (d) {
return {
"x": d.source.x,
"y": d.source.y + 150
};
})
.projection(function (d) { return [d.y + 0, d.x + 0];
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? 15 : 15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", 60)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? -15 : -15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 150)
.attr("height", 30)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1)
.attr("text-anchor", "middle");
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? 15 : 15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 10)
.attr("height", 10);
nodeExit.select("text")
.style("fill-opacity", 1e-6)
.attr("text-anchor", "middle");
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("fill", "none")
.attr("stroke", "black")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
</script>
Just a superficial attempt.
First add all the text elements
Wrap the text element within certain width using tspans
Get the height of the text element and store as an attribute it in the data itself
Use the stored attribute for setting the height of the rectangle
Reference for wrapping text here. You can always write custom wrapping function.
Hope this helps
var treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A. Some text here Some text here Some text here Some text here",
"parent": "Top Level",
"children": [
{
"name": "Son of A Some text here Some text here",
"parent": "Level 2: A"
},
{
"name": "Daughter of A Some text here Some text here Some text here Some text here Some text here",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B Some text here Some text here Some text here",
"parent": "Top Level"
}
]
}
];
// ************** Generate the tree diagram *****************
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.source(function (d) {
return {
"x": d.source.x,
"y": d.source.y + 150
};
})
.projection(function (d) { return [d.y + 0, d.x + 0];
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? 15 : 15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", 60)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6)
.each(function(d) {
calculateTextWrap(this,d);
});
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? -15 : -15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 150)
.attr("height", function(d) { return d.rectHeight})
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1)
.attr("text-anchor", "middle");
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("rect")
.attr("x", function(d) { return d.children || d._children ? 0 : 0; })
.attr("y", function(d) { return d.children || d._children ? 15 : 15; })
.attr("rx", 10)
.attr("ry", 10)
.attr("width", 10)
.attr("height", 10);
nodeExit.select("text")
.style("fill-opacity", 1e-6)
.attr("text-anchor", "middle");
function calculateTextWrap(element, data) {
var text = d3.select(element);
if (text.node().getComputedTextLength() < 150) {
//console.log("No need to wrap");
} else {
var words = text.text().split("").reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(0.35),
tspan = text.text(null).append("tspan").attr("text-anchor", "start").attr("x", 5).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(""));
if (tspan.node().getComputedTextLength() > 150) {
lineNumber++;
line.pop();
tspan.text(line.join(""));
line = [word];
tspan = text.append("tspan").attr("text-anchor", "start").attr("x", 5).attr("y", y).attr("dy", lineHeight + dy + "em").text(word);
}
}
}
var rectHeight = text.node().getBBox().height;
if(rectHeight < 30) rectHeight = 30;
data.rectHeight = rectHeight + 10 ;
}
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("fill", "none")
.attr("stroke", "black")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
.node {
cursor: pointer;
border-style: solid;
border-width: 2px 10px 4px 20px;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node rect {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>
try to add this to your styling :
.node {
height: fit-content;
width: fit-content;
padding: .5rem;
}
It fits the height and size of the node class to the content (text) of the element. It should do the trick.

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

Blank page using d3 mbostock

I have very new to d3 so please bear with me. The problem I am having is that I cannot get nor figure out why none of the http://bl.ocks.org/mbostock/ demos work after copying a pasting. I keep get blank or white pages. What am I missing?
I even downloaded the gist source file from https://gist.github.com/mbostock/3884955 and still it did not work.
Any ideas will be much appreciated because I also need to implement http://bost.ocks.org/mike/uberdata/ with its data files:
(1) http://bost.ocks.org/mike/uberdata/citites.csv
(2) http://bost.ocks.org/mike/uberdata/matrix.json
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - 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.temperature); });
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[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var cities = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, temperature: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }),
d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
]);
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("Temperature (ºF)");
var city = svg.selectAll(".city")
.data(cities)
.enter().append("g")
.attr("class", "city");
city.append("path")
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - 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.temperature); });
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[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var cities = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, temperature: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(cities, function(c) { return d3.min(c.values, function(v) { return v.temperature; }); }),
d3.max(cities, function(c) { return d3.max(c.values, function(v) { return v.temperature; }); })
]);
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("Temperature (ºF)");
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.temperature) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
});
</script>
</body>
</html>
You most likely get this message in your console:
XMLHttpRequest cannot load file:///C:/Users/Charles/Desktop/New%20folder/data.tsv. Cross origin requests are only supported for HTTP.
You need to be using a webserver in order to run this script. You might also be able to get around it within your browser settings. This is because an http request is not made by loading this file.
It is explained here how to get around this. It shouldn't take too long to set up and it will make local development much easier for you. Good luck!