how to replace comma with dot - html

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/

Related

D3 - Updating Choropleth csv to change mapping of colours

Hi I'm new to D3 and am having trouble updating my map through buttons that trigger a function to load a new csv. I looked at similar posts which mentioned that I would only need to update the section which fills the map with colours, and have tried to adapt this but clicking on my button doesn't affect the map.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Setting path fills dynamically to generate a choropleth</title>
<h1>Relation between Managers and Tertiary Education </h1>
<div id="option1">
<input type="button"value="Education"onclick="viewEducation()" />
</div>
<div id="option2">
<input type="button"value="Managers"onclick="viewManagers()" />
</div>
<script type="text/javascript" src="d3.js"></script>
<style type="text/css">
/* No style rules here yet */
</style>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 1000;
var h = 600;
var path = d3.geoPath()
.projection(d3.geoMercator()
.center([151,-33.5])
.scale(17000)
.translate([w/2,h/2]));
//Define quantize scale to sort data values into buckets of color
var color = d3.scaleQuantize()
.range(["rgb(237,248,233)","rgb(200,235,198)", "rgb(186,228,179)","rgb(146,208,140)", "rgb(116,196,118)", "rgb(88,178,100)", "rgb(49,163,84)", "rgb(20,130,60)", "rgb(0,109,44)"])
.domain([6274, 39796]);
//Colors derived from ColorBrewer, by Cynthia Brewer, and included in
//https://github.com/d3/d3-scale-chromatic
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
//Load in agriculture data
d3.csv("ManagerPercentage.csv", function(d) { d.value = parseFloat(d.value); parseFloat(d.value1); return d; }, function(data) {
//Set input domain for color scale
color.domain([
d3.min(data, function(d) { return d.value; }),
d3.max(data, function(d) { return d.value; })
]);
//Load in GeoJSON data
d3.json("australia_adm2.json", function(json) {
//Merge the ag. data and GeoJSON
//Loop through once for each ag. data value
for (var i = 0; i < data.length; i++) {
//Grab state name
var dataState = data[i].state;
//Grab data value, and convert from string to float
var dataValue = parseFloat(data[i].value);
//Find the corresponding state inside the GeoJSON
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.sa4_name11;
if (dataState == jsonState) {
//Copy the data value into the JSON
json.features[j].properties.value = dataValue;
//Stop looking through the JSON
break;
}
}
}
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
//Get data value
var value = d.properties.value;
if (value) {
//If value exists…
return color(value);
} else {
//If value is undefined…
return "#ccc";
}
});
});
});
function viewEducation () {
d3.select("option1")
d3.csv("EducationPercentage.csv", function(data) {
svg.selectAll("path")
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return "#ccc";
}
});
});
}
function viewManagers () {
d3.select("option2")
d3.csv("ManagerPercentage.csv", function(data) {
svg.selectAll("path")
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
} else {
return "#ccc";
}
});
});
});
}
</script>
</body>
</html>

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>

Using dynamic input(CSV) in d3js

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

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.