Using dynamic input(CSV) in d3js - html

I am trying to use dynamic input to a draw function in d3js. So when the user changes the csv it would remove the current selection and draw the visualization for the new input. So my question is would I be using a onChange function with the select and then within this function parse the csv and call for the draw function.The current working code is here in plunker:
https://plnkr.co/edit/AjVBK3rTOF5aI4eDDbV5?p=preview
<svg width="1250" height="1080"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width");
var format = d3.format(",d");
var color = d3.scaleOrdinal(d3.schemeCategory10);
var pack = d3.pack()
.size([width, width])
.padding(1.5);
var inputs = {};
function selectCity(){
//storing the drop-dsown selection in the ddSelection var
var ddSelection = document.getElementById("city").value;
//feeding that to create the csv filename you want
var str1 = ddSelection;
var str2 = ".csv";
var csvFile = str1.concat(str2);
str1.concat(str2);
console.log(csvFile);
d3.csv(csvFile, function(d) {
d.sno = +d.sno;
return d;
}, function(error, data) {
if (error) throw error;
d3.selectAll("input").on("change", function(){
inputs[this.id] = +this.value;
console.log(inputs.myValue + "-" + inputs.myRating)
if(inputs.myValue && inputs.myRating){
var classes = data.filter(d => d.value < inputs.myValue && d.rating >= inputs.myRating);
draw(classes);
}
})
function draw(classes) {
console.log(classes.length);
var root = d3.hierarchy({
children: classes
})
.sum(function(d) {
return d.value;
})
.each(function(d) {
if (id = d.data.id) {
var id, i = id.lastIndexOf(".");
d.id = id;
d.package = id.slice(0, i);
d.class = id.slice(i + 1);
}
});
var node = svg.selectAll(".node")
.data(pack(root).leaves())
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
node.append("circle")
.attr("id", function(d) {
return d.id;
})
.attr("r", function(d) {
return d.r;
})
.style("fill", function(d) {
return color(d.package);
});
node.append("clipPath")
.attr("id", function(d) {
return "clip-" + d.id;
})
.append("use")
.attr("xlink:href", function(d) {
return "#" + d.id;
});
node.append("text")
.attr("clip-path", function(d) {
return "url(#clip-" + d.id + ")";
})
.selectAll("tspan")
.data(function(d) {
return d.class.split(/(?=[A-Z][^A-Z])/g);
})
.enter().append("tspan")
.attr("x", 0)
.attr("y", function(d, i, nodes) {
return 13 + (i - nodes.length / 2 - 0.5) * 10;
})
.text(function(d) {
return d;
});
node.append("title")
.text(function(d) {
return d.data.id + "\n" + format(d.value);
});
}
});
}
</script>
</div>

Here is one example how to do it: http://www.d3noob.org/2014/04/using-html-inputs-with-d3js.html
You don't have to redraw everything but update certain elements.
I don't understand your part about changing the CSV. The user does not change the CSV but your visual output is depending on some user data. So yes, within the callback function of d3.csv(), you write your code that calls some kind of a draw function. But the draw function does not have to be defined there. You can write the function outside and just call it there. This increased the readable of your code dramatically. ;)

Related

How to transform code from a tsv import to direct data

I'm working with some D3 examples in php driven pages. I've found a great example I want to use of a line chart with inline lables (full code here: https://bl.ocks.org/mbostock/4b66c0d9be9a0d56484e), but I can't figure out how to transition the code from a tsv import to an array provided directly from the database.
I am obviously providing the data directly like this:
var data = [
{date:2009, Apples:130, Bananas:40},
{date:2010, Apples:137, Bananas:58},
{date:2011, Apples:166, Bananas:97},
{date:2012, Apples:154, Bananas:117},
{date:2013, Apples:179, Bananas:98},
{date:2014, Apples:187, Bananas:120},
{date:2015, Apples:189, Bananas:84}
]
And then I'm trying to replace this chunk of code that handles the import and the sorting into an array automatically.
d3.requestTsv("data.tsv", function(d) {
d.date = parseTime(d.date);
for (var k in d) if (k !== "date") d[k] = +d[k];
return d;
}, function(error, data) {
if (error) throw error;
var series = data.columns.slice(1).map(function(key) {
return data.map(function(d) {
return {
key: key,
date: d.date,
value: d[key]
};
});
});
But I think I'm having problems replicating the portion that creates the series.
I've tried several variations of this:
var series = data.map(function(key) {
return data.map(function(d) {
return {
key: key,
date: d.date,
value: d[key]
};
});
});
followed with a function to set the data type at the end of the code:
function type(d) {
d.date = parseTime(d.date);
for (var k in d) if (k !== "date") d[k] = +d[k];
return d;
}
But nothing seems to work. I'm sure there is something simple I'm missing, but what should I specifically be changing here to use code by providing the data directly in an array instead of a tsv import?
Your data array is correct (regarding the TSV in Bostock's code).
However, you have two problems:
The d3.tsv function creates an array property named columns. Since you're ditching d3.tsv and using a variable to store the data, you'll have to create that array yourself:
data.columns = ["date", "Apples", "Bananas"]
The d3.tsv accepts a row function. Again, since you're using a variable to store the data, you'll have to use a forEach to do what the row function does in Bostock's code:
data.forEach(d=>{
d.date = parseTime(d.date);
for (var k in d) if (k !== "date") d[k] = +d[k];
});
Here is the updated code using a variable to store the data: https://bl.ocks.org/anonymous/749f2c5bc6a42d68bca3ec579646ff1d
And here the same code in the Stack snippet:
<style>
text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke-width: 1.5px;
}
.label {
text-anchor: middle;
}
.label rect {
fill: white;
}
.label-key {
font-weight: bold;
}
</style>
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.0.0-alpha.9.min.js"></script>
<script>
var parseTime = d3.timeParse("%Y");
var svg = d3.select("svg");
var margin = {top: 30, right: 50, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
labelPadding = 3;
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data = [
{date:2009, Apples:130, Bananas:40},
{date:2010, Apples:137, Bananas:58},
{date:2011, Apples:166, Bananas:97},
{date:2012, Apples:154, Bananas:117},
{date:2013, Apples:179, Bananas:98},
{date:2014, Apples:187, Bananas:120},
{date:2015, Apples:189, Bananas:84}
];
data.columns = ["date", "Apples", "Bananas"]
data.forEach(d=>{
d.date = parseTime(d.date);
for (var k in d) if (k !== "date") d[k] = +d[k];
});
var series = data.columns.slice(1).map(function(key) {
return data.map(function(d) {
return {
key: key,
date: d.date,
value: d[key]
};
});
});
var x = d3.scaleTime()
.domain([data[0].date, data[data.length - 1].date])
.range([0, width]);
var y = d3.scaleLinear()
.domain([0, d3.max(series, function(s) { return d3.max(s, function(d) { return d.value; }); })])
.range([height, 0]);
var z = d3.scaleCategory10();
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
var serie = g.selectAll(".serie")
.data(series)
.enter().append("g")
.attr("class", "serie");
serie.append("path")
.attr("class", "line")
.style("stroke", function(d) { return z(d[0].key); })
.attr("d", d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.value); }));
var label = serie.selectAll(".label")
.data(function(d) { return d; })
.enter().append("g")
.attr("class", "label")
.attr("transform", function(d, i) { return "translate(" + x(d.date) + "," + y(d.value) + ")"; });
label.append("text")
.attr("dy", ".35em")
.text(function(d) { return d.value; })
.filter(function(d, i) { return i === data.length - 1; })
.append("tspan")
.attr("class", "label-key")
.text(function(d) { return " " + d.key; });
label.append("rect", "text")
.datum(function() { return this.nextSibling.getBBox(); })
.attr("x", function(d) { return d.x - labelPadding; })
.attr("y", function(d) { return d.y - labelPadding; })
.attr("width", function(d) { return d.width + 2 * labelPadding; })
.attr("height", function(d) { return d.height + 2 * labelPadding; });
</script>

how to replace comma with dot

I am having comma values inside my json and i want when i get those values i get them in dot so basically I want to convert my comma values into dot values..my json looks like and its always fixed that i will get comma values at val003.
I know something to do like var new = new.replace(/,/g, '.') . but how can i specify my val003 here for the conversion. Thank you in advance
My html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta content="utf-8" http-equiv="encoding">
<div id="below">
<div id="chart"></div>
</div>
<script>
var jsonURL = 'avb.json';
var myData = [];
var fliterdata = [];
var tempdata = [];
var selectop = "";
var selectDate = false;
var chartType = chartType || 'bar';
function filterJSON(json, key, value) {
var result = [];
for (var foo in json) {
var extractstr = json[foo][key] ;
extractstr=String(extractstr);
if (extractstr.slice(3)== value) {
result.push(json[foo]);
}
}
return result;
}
function selectValue(d) {
switch (selectop) { //d object select particular value for Y axis
case "01":
return d.val001;
break;
case "02":
return d.val002;
break;
case "03":
return d.val003;
break;
case "04":
return d.val004;
break;
default:
//console.log("default");
return d.val001;
}
}
var line = d3.svg.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(selectValue(d));
})
.interpolate("monotone")
.tension(0.9);
yScale.domain([0, d3.max(tempData, function(d) {
return +selectValue(d);
})]);
var svg = d3.select('#chart').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 + ")");
if (chartType == 'bar') {
svg
.selectAll(".bar") //makes bar
.data(tempData)
.enter().append("rect")
.attr("class", "bar")
.style("fill", "teal")
.attr("x", function(d) {
return xScale(d.date);
}).attr("width", xScale.rangeBand())
.attr("y", function(d) {
return yScale(selectValue(d));
}).attr("height", function(d) {
console.log("as", d.value);
return height - yScale(selectValue(d));
})
}
if (chartType == 'line') {
svg.append("path") // Add the line path.
.data(tempData)
.attr("class", "line")
.attr("d", line(tempData));
}
}
d3.json(jsonURL, function(data) {
myData = data; //data from json in mydata
d.val003.replace(",",".")
myData.forEach(function(d) {
d.date = new Date(d.date);
d.date = new Date(d.date + " UTC");
});
$("#listbox").on("click", function() {
var key = $(this).val();
console.log("key:", key);
var value = $('#listbox option:selected').text();
console.log("vaue:", value);
selectop = String(key);
selectop = selectop.slice(-2);
console.log("mydata: ", myData);
console.log("selectops:", selectop);
fliterdata = filterJSON(myData, key, value); //selected value from user and picks the whole element that contains that attribute
console.log("fliterdata: ", fliterdata);
tempData = fliterdata; //graph made by temp data
if (selectDate)
render(true);
});
});
function selectChartType(type) {
chartType = type;
render(true);
}
</script>
</body>
</div>
</body>
</html>
Try this,
return d.val003.toString().replace(",",".");
Yo can simply request a value in a JSon object -- it pretty much serves as an object in JavaScript.
So if you have your JSon object, lets call it json you can simply do:
var url = *your url*, json;
// retrieve the json object from a URL
$.getJSON(url, function (response) {$
json = response;
});
// reassing val003 with the corrected string
json.val003 = json.val003.replace(",", ".")
That should work, I believe.
If it is always the comma in a decimal number you want to replace, than you can do a search replace in the whole json string for the sequence "number" "comma" "number" like:
([0-9]),([0-9])
and replace it with:
$1.$2
$1 and $2 are the placeholders for the found numbers before and after the comma.
You can use this site for online testing:
http://www.regexe.com/

Django d3.js in HTML file not loading unless I manually open HTML file

I'm trying to implement a bubble chart on a webpage using the Django framework and the D3.js framework. I have an HTML file, and my data is stored in a JSON file.
Accessing the JSON file seems fine, because when I manually open the HTML file in my browser it works/loads fine, however, when I hit the webpage URL endpoint via Django, the D3 part of the page just shows blank (console says "node is undefined"). I am using the example code given here.
Any help would be very appreciated. Thanks.
D3 js code:
<script src="http://d3js.org/d3.v3.min.js"></script>
<div class="cloud">
<script>
var diameter = 960,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
d3.json("cloud.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return color(d.packageName); });
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.className.substring(0, d.r / 3); });
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
}
d3.select(self.frameElement).style("height", diameter + "px");
</script>

how to take json from veriable in d3 chart

I am using D3 to plot bubble chart using data in json format to plot bubble chart
My json format is like:{"children":[
{"name":"1","size":0.5},
{"name":"3","size":0.3636},
{"name":"4","size":0.5652},
{"name":"5","size":19.5556},
{"name":"6","size":1.037},
{"name":"7","size":0.7048},
{"name":"8","size":2.2593},
{"name":"9","size":13.7407},
{"name":"10","size":4.2222},
{"name":"11","size":2.6667},
{"name":"12","size":0.7037},
{"name":"13","size":20.6296},
{"name":"14","size":17.7037},
{"name":"15","size":2.1481},
{"name":"16","size":3.4815},
{"name":"17","size":0.1852},
{"name":"18","size":0.087},
{"name":"19","size":15.68}
]}
I am accessing this json as:
d3.json("flare.json", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
now i want to access from veriable
var datasource={"children":[
{"name":"1","size":0.5},
{"name":"3","size":0.3636},
{"name":"4","size":0.5652},
{"name":"5","size":19.5556},
{"name":"6","size":1.037},
{"name":"7","size":0.7048},
{"name":"8","size":2.2593},
{"name":"9","size":13.7407},
{"name":"10","size":4.2222},
{"name":"11","size":2.6667},
{"name":"12","size":0.7037},
{"name":"13","size":20.6296},
{"name":"14","size":17.7037},
{"name":"15","size":2.1481},
{"name":"16","size":3.4815},
{"name":"17","size":0.1852},
{"name":"18","size":0.087},
{"name":"19","size":15.68}
]}
I have tried like:
JSON.parse("dataSource", function(error, root) {
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(root))
.filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
but unable to get result where i am going wrong.please reply me.
Thanks
prashansa
datasource is variable not string
so try this
JSON.parse(dataSource, function(error, root) {
EDITED
var dataSource = '{"children":...'; //JSON.parse needed
//so your code would be
JSON.parse(dataSource, function(error, root) {
var dataSource = {"children":...}; //JSON.parse not needed
//so your code would be
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(dataSource))
.filter(function(d) { return !d.children; }))

Updating links on a force directed graph from dynamic json data

I am new to D3 and working on a force directed graph where the json data is dynamic. I am able to change the force graph upon receiving new data but that happens with a springing effect. The code that creates my force graph is :
<div class="graph"></div>
<script>
var w = 660,
h = 700,
r = 10;
var vis = d3.select(".graph")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("pointer-events", "all")
.append('svg:g')
.call(d3.behavior.zoom().on("zoom", redraw))
.append('svg:g');
vis.append('svg:rect')
.attr('width', w)
.attr('height', h)
.attr('fill', 'rgba(1,1,1,0)');
function redraw() {
console.log("here", d3.event.translate, d3.event.scale);
vis.attr("transform", "translate(" + d3.event.translate + ")" +
" scale(" + d3.event.scale + ")");
};
var force = d3.layout.force()
.gravity(.05)
.charge(-200)
.linkDistance( 260 )
.size([w, h]);
var svg = d3.select(".text")
.append("svg")
.attr("width", w)
.attr("height", h);
d3.json(graph, function(json) {
var nodeList = json.nodes;
var link = vis.selectAll("line")
.data(json.links)
.enter()
.append("line")
.attr("stroke-opacity", function(d) {
if(d.label == 'is a') {
return '0.8';
} else {
return '0.2';
};
})
.attr("stroke-width", function(d) {
if(d.value !== null) {
return d.value;
} else {
return 2;
};
})
.style("stroke", function(d) {
if(d.color !== null) {
return d.color;
};
})
.on("mouseover", function() {
d3.select(this)
.style("stroke", "#999999")
.attr("stroke-opacity", "1.0");
})
.on("mouseout", function() {
d3.select(this)
.style("stroke", function(d) {
if(d.color !== null) {
return d.color;
};
})
.attr("stroke-opacity", function(d) {
if(d.label == 'is a') {
return '0.8';
} else {
return '0.2';
};
})
});
link.append("title")
.text(function(d) { return d.label } );
var node = vis.selectAll("g.node")
.data(json.nodes)
.enter()
.append("svg:g")
.attr("class","node")
.call(force.drag);
node.append("svg:circle")
.attr("r", function(d) {
if (d.size > 0) {
return 10+(d.size*2);
} else {
return 10;
}
})
.attr("id", function(d) { return "Node;"+d.id; } )
.style("fill", function(d) {
if(d.style == 'filled') {
return d.color;
};
})
.style("stroke", function(d) {
if(d.style !== 'filled') {
return d.color;
};
})
.style("stroke-width", "2")
.on("mouseover", function() {
d3.select(this).style("fill", "#999");
fade(.1);
})
.on("mouseout", function(d) {
if (d.style == 'filled') {
d3.select(this).style("fill",d.color);fade(1);
} else {
d3.select(this).style("stroke",d.color);
d3.select(this).style("fill","black");
}
fade(1);
});
node.append("title")
.text(function(d) { return d.Location; } );
force.nodes(json.nodes)
.links(json.links)
.on("tick", tick)
.alpha(1)
.start();
function tick() {
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
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; });
}
});
</script>
I am able to create a new graph when a new json string is received by recalling the whole function again. This creates a new graph in place of the old. I am unable to update the old graph with the new set of values as the values are received; the nodes in my graph do not change, just the relation among them changes.
I did stumble upon an example (http://bl.ocks.org/1095795) where a new node is deleted and recreated, but the implementation is a bit different.
Any pointers or help will be really appreciated.
Well I could find the solution browsing through, posting it here for anyone needing help on this topic. The idea is to create an object of the graph and playing around with the nodes and links arrays.
The JS code goes as:
var graph;
function myGraph(el) {
// Add and remove elements on the graph object
this.addNode = function (id) {
nodes.push({"id":id});
update();
};
this.removeNode = function (id) {
var i = 0;
var n = findNode(id);
while (i < links.length) {
if ((links[i]['source'] == n)||(links[i]['target'] == n))
{
links.splice(i,1);
}
else i++;
}
nodes.splice(findNodeIndex(id),1);
update();
};
this.removeLink = function (source,target){
for(var i=0;i<links.length;i++)
{
if(links[i].source.id == source && links[i].target.id == target)
{
links.splice(i,1);
break;
}
}
update();
};
this.removeallLinks = function(){
links.splice(0,links.length);
update();
};
this.removeAllNodes = function(){
nodes.splice(0,links.length);
update();
};
this.addLink = function (source, target, value) {
links.push({"source":findNode(source),"target":findNode(target),"value":value});
update();
};
var findNode = function(id) {
for (var i in nodes) {
if (nodes[i]["id"] === id) return nodes[i];};
};
var findNodeIndex = function(id) {
for (var i=0;i<nodes.length;i++) {
if (nodes[i].id==id){
return i;
}
};
};
// set up the D3 visualisation in the specified element
var w = 500,
h = 500;
var vis = d3.select("#svgdiv")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("id","svg")
.attr("pointer-events", "all")
.attr("viewBox","0 0 "+w+" "+h)
.attr("perserveAspectRatio","xMinYMid")
.append('svg:g');
var force = d3.layout.force();
var nodes = force.nodes(),
links = force.links();
var update = function () {
var link = vis.selectAll("line")
.data(links, function(d) {
return d.source.id + "-" + d.target.id;
});
link.enter().append("line")
.attr("id",function(d){return d.source.id + "-" + d.target.id;})
.attr("class","link");
link.append("title")
.text(function(d){
return d.value;
});
link.exit().remove();
var node = vis.selectAll("g.node")
.data(nodes, function(d) {
return d.id;});
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("r", 16)
.attr("id",function(d) { return "Node;"+d.id;})
.attr("class","nodeStrokeClass");
nodeEnter.append("svg:text")
.attr("class","textClass")
.text( function(d){return d.id;}) ;
node.exit().remove();
force.on("tick", function() {
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
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; });
});
// Restart the force layout.
force
.gravity(.05)
.distance(50)
.linkDistance( 50 )
.size([w, h])
.start();
};
// Make it all go
update();
}
function drawGraph()
{
graph = new myGraph("#svgdiv");
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addLink('A','B','10');
graph.addLink('A','C','8');
graph.addLink('B','C','15');
}
I took Rahuls great example, made some changes, and posted a bl.ock complete with animation over time if anyone is interested in a fully functioning example. Adding/removing links/nodes really should be easier than this, but still pretty cool.
http://bl.ocks.org/ericcoopey/6c602d7cb14b25c179a4
In addition to calling drawGraph() in the ready function, you can also embed the posted code inside an inline <script></script>block.
This is how most of the tutorials on the d3 site handle it.