Simple example of d3.js not working - javascript

Here is simple html, which will have 2 circle and label on it
<!DOCTYPE html>
1<html>
<head>
<script type="text/javascript" src="d3.min.js"></script>
<script type="text/javascript" src="simple.js"></script>
<link href="style 2.css" type="text/css" rel="stylesheet">
</head>
<body>
<h1>Test</h1>
<div id="small-gr"></div>
</body>
</html>
simple.js this is simple example for d3 dashing site .
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];
//Create the SVG Viewport
var svgContainer = d3.selectAll("body").append("svg")
.attr("width",200)
.attr("height",200);
//Add circles to the svgContainer
var circles = svgContainer.selectAll("circle")
.data(circleData)
.enter()
.append("circle");
// //Add the circle attributes
var circleAttributes = circles
.attr("cx", function (d) { return d.cx; })
.attr("cy", function (d) { return d.cy; })
.attr("r", function (d) { return d.radius; })
.style("fill", function (d) { return d.color; });
//Add the SVG Text Element to the svgContainer
var text = svgContainer.selectAll("text")
.data(circleData)
.enter()
.append("text");
//Add SVG Text Element Attributes
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
Our problem is very weird , if you see the <html> tag you can find 1 there , that's what we have to use so that the code works, but if you remove it the code doesn't work , this has no edit it's directly taken from d3 site. Can anyone explain why is this happening ?

Related

D3.select(this) but filter

I am working on an D3 forced graph and got a challenge. I added a "mouseenter" function which increase the radius of nodes if getting hovered.
.on("mouseenter", function(d) {
d3.select(this)
.transition()
.duration(200)
.attr("r", 50)
Now I want to exclude certain nodes and thought to filter would help. Unfortunately it doesn´t. Probably my code is wrong or I need to add those filtering later one. Any idea?
.on("mouseenter", function(d) {
d3.select(this)
.filter(function() {
return !this.graph.nodes.name("usv"))
})
.transition()
.duration(200)
.attr("r", 50)
Best,
Kristian
Here's an example implementation:
<!doctype html>
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg width="500" height="500"></svg>
<script>
let data = d3.range(10)
.map(function(d){
return {
name: Math.random() > 0.5 ? "usv" : "na",
x: Math.random() * 480,
y: Math.random() * 480
};
});
d3.select('svg')
.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', 20)
.attr("fill", d => d.name == "usv" ? "red" : "black")
.filter((d) => {
return d.name === "usv";
})
.on("mouseenter", function(){
d3.select(this)
.transition()
.duration(200)
.attr("r", 50);
});
</script>
</body>
</html>

The bubble chart d3 doesn't work

I'm trying to make a bubble chart for class, but somehow it doesn't work at all, I checked the code again and again, couldn't find what's wrong with it.
<!DOCTYPE html>
<html>
<head>
<title>bubble</title>
<script src="https://d3js.org/d3.v3.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
var diameter = 500, //max size of the bubbles
color = d3.scale.category20b(); //color category
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.csv("fruit.csv", function(error, data){
//convert numerical values from strings to numbers
data = data.map(function(d){ d.value = +d["Amount"]; return d; });
//bubbles needs very specific format, convert data to this.
var nodes = bubble.nodes({children:data}).filter(function(d) { return !d.children; });
//setup the chart
var bubbles = svg.append("g")
.attr("transform", "translate(0,0)")
.selectAll(".bubble")
.data(nodes)
.enter();
//create the bubbles
bubbles.append("circle")
.attr("r", function(d){ return d.r; })
.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; })
.style("fill", function(d) { return color(d.value); });
//format the text for each bubble
bubbles.append("text")
.attr("x", function(d){ return d.x; })
.attr("y", function(d){ return d.y + 5; })
.attr("text-anchor", "middle")
.text(function(d){ return d["Fruit"]; })
.style({
"fill":"white",
"font-family":"Helvetica Neue, Helvetica, Arial, san-serif",
"font-size": "12px"
});
})
</script>
</html>
And this is the data file I'm using, the file name is fruit.csv. I did check everything line by line, couldn't find anything wrong
Fruit,Amount
Apple,32
Orange,89
Banana,15

Insert text inside Circle in D3 chart

I want to insert some text inside my Circle which is plot in bubble chart using D3.js.
I am able to draw circle in svg as per the data provided to it, but facing a problem while append text to it.
below is my code:
<script type="text/javascript">
var sampleData = [{"x": 8,"y": 1}, {"x": 2,"y": 1}, {"x": 4,"y": 1},{"x": 5,"y": 1}];
// {"x": 6,"y": 40}, {"x": 8,"y": 100}, {"x": 10,"y": 60}];
$(function() {
InitChart();
});
function InitChart() {
// Chart creation code goes here
var vis = d3.select("#svgVisualize");
var xRange = d3.scale.linear().range([40, 400]).domain([0,10]);
var yRange = d3.scale.linear().range([200, 40]).domain([0,2]);
/* var xRange = d3.scale.linear().range([40, 400]).domain([d3.min(sampleData, function(d) {
return (d.x);
}), d3.max(sampleData, function(d) {
return d.x;
})]);
var yRange = d3.scale.linear().range([400, 40]).domain([d3.min(sampleData, function(d) {
return d.y;
}), d3.max(sampleData, function(d) {
return d.y;
})]); */
var xAxis = d3.svg.axis().scale(xRange).ticks(2);
var yAxis = d3.svg.axis().scale(yRange).ticks(2).orient("left");
vis.append("svg:g").call(xAxis).attr("transform", "translate(0,200)");
vis.append("svg:g").call(yAxis).attr("transform", "translate(40,0)");
var circles = vis.selectAll("circle").data(sampleData);
circles
.enter()
.insert("circle")
.attr("cx", function(d) { return xRange (d.x); })
//.attr("cy", function(d) { return yRange (d.y); })
.attr("cy", function(d) { return yRange (d.y); })
.attr("r", function(d) { return Math.log(d.x) * 30; })
.attr("stroke","black")
.style("fill", "yellow");
var text = vis.selectAll("text")
.data(sampleData)
.enter()
.insert("text");
//Add SVG Text Element Attributes
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
}
</script>
<body>
<svg id="svgVisualize" width="500" height="250" style="border:1px solid Red;"></svg>
</body>
Can anyone suggest what is the problem with above code?
Thanks
When you do this:
var text = vis.selectAll("text")
.data(sampleData)
.enter()
.insert("text");
You are selecting <text> elements that already exist in that SVG (in your case, the axes' ticks). Because of that, your "enter" selection is empty.
Solution: select something that doesn't exist, like null:
var text = vis.selectAll(null)
.data(sampleData)
.enter()
.insert("text");
Here is the updated code:
var sampleData = [{
"x": 8,
"y": 1
}, {
"x": 2,
"y": 1
}, {
"x": 4,
"y": 1
}, {
"x": 5,
"y": 1
}];
var vis = d3.select("svg");
var xRange = d3.scale.linear().range([40, 400]).domain([0, 10]);
var yRange = d3.scale.linear().range([200, 40]).domain([0, 2]);
var xAxis = d3.svg.axis().scale(xRange).ticks(2);
var yAxis = d3.svg.axis().scale(yRange).ticks(2).orient("left");
vis.append("svg:g").call(xAxis).attr("transform", "translate(0,200)");
vis.append("svg:g").call(yAxis).attr("transform", "translate(40,0)");
var circles = vis.selectAll("circle").data(sampleData);
circles
.enter()
.append("circle")
.attr("cx", function(d) {
return xRange(d.x);
})
//.attr("cy", function(d) { return yRange (d.y); })
.attr("cy", function(d) {
return yRange(d.y);
})
.attr("r", function(d) {
return Math.log(d.x) * 30;
})
.attr("stroke", "black")
.style("fill", "yellow");
var text = vis.selectAll(null)
.data(sampleData)
.enter()
.append("text");
var textLabels = text
.attr("x", function(d) {
return xRange(d.x);
})
.attr("text-anchor", "middle")
.attr("y", function(d) {
return yRange(d.y);
})
.text(function(d) {
return "( " + d.x + ", " + d.y + " )";
})
.attr("font-family", "sans-serif")
.attr("font-size", "10px")
.attr("fill", "red");
line, path{
fill: none;
stroke: black;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg width="400" height="220"></svg>
PS: Don't use insert, use append instead.
A better way of doing this is to use svg groups, then you can position both the circles and the text together:
var join = vis.selectAll(".points").data(sampleData);
var groups = join
.enter()
.append("g")
.attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")"; });
.attr("cx", function(d) { return xRange (d.x); })
groups.append("circle")
.attr("r", function(d) { return Math.log(d.x) * 30; })
.attr("stroke","black")
.style("fill", "yellow");
groups.append("text")
.data(sampleData)
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");

How to draw lines between circles?

I'm attemtping to draw three circles and draw connected lines between each of these circles.
The end goal is to configure what circles are connected using json configuration but prior to this im just trying to connect the circles using the callbacks and hard code values.
Here is what I have so far :
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body style="overflow: hidden;">
<div id="canvas" style="overflow: hidden;"></div>
<script type="text/javascript">
var graph = {
"nodes":[
{"name":"1","group":1, "x" : 100, "y" : 100 , r : 20},
{"name":"2","group":1, "x" : 200, "y" : 150 ,r : 30},
{"name":"3","group":2 , "x" : 300, "y" : 250 , r : 50}
],
"links":[
{"source":1,"target":0,"value":1}
]
}
var width = 2000;
var height = 500;
var svg = d3.select("#canvas").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var lines = svg.attr("class", "line")
.selectAll("line").data(graph.links)
.enter().append("line")
.attr("x1", function(d) { return 50 })
.attr("y1", function(d) { return 50 })
.attr("x2", function(d) { return 100 })
.attr("y2", function(d) { return 100 })
var circles = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", function(d, i){ return d.r })
.attr("cx", function(d, i){ return d.x })
.attr("cy", function(d, i){ return d.y })
</script>
</body>
</html>
But no lines are being drawn. Each circle should contain a single line connecting it to the other circle.
I'm just hard coding the x1,y1,x2,y2 co-ordinates but I will be using the
co-ordinates of the other circles in order to determine the postions of the lines. Why are the lines not being drawn ? Is there standard d3 methods I should be utilising in order to connect these circles ?
fiddle : http://jsfiddle.net/zzz8svuq/10/
Update :
Here is the updated code which draws connected lines between circles as configured in dataset graph.nodes :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body style="overflow: hidden;">
<div id="canvas" style="overflow: hidden;"></div>
<script type="text/javascript">
var graph = {
"nodes": [
{name: "1", "group": 1, x: 100, y: 50, r: 10 , connected : "2"},
{name: "2", "group": 1, x: 200, y: 90, r: 15, connected : "1"},
{name: "3", "group": 2, x: 300, y: 230, r: 25, connected : "1"}
]
}
$( document ).ready(function() {
var width = 2000;
var height = 500;
var svg = d3.select("#canvas").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var lines = svg.attr("class", "line")
.selectAll("line").data(graph.nodes)
.enter().append("line")
.style("stroke", "gray") // <<<<< Add a color
.attr("x1", function (d, i) {
return d.x
})
.attr("y1", function (d) {
return d.y
})
.attr("x2", function (d) {
return findAttribute(d.connected).x
})
.attr("y2", function (d) {
return findAttribute(d.connected).y
})
var circles = svg.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", function (d, i) {
return d.r
})
.attr("cx", function (d, i) {
return d.x
})
.attr("cy", function (d, i) {
return d.y
});
});
function findAttribute(name) {
for (var i = 0, len = graph.nodes.length; i < len; i++) {
if (graph.nodes[i].name === name)
return graph.nodes[i]; // Return as soon as the object is found
}
return null; // The object was not found
}
</script>
</body>
</html>
You need to make sure that the lines have a stroke color or else they will be drawn white and you won't be able to see them.
var lines = svg.attr("class", "line")
.selectAll("line").data(graph.links)
.enter().append("line")
.style("stroke", "gray") // <<<<< Add a color
.attr("x1", function(d) { return 50 })
.attr("y1", function(d) { return 50 })
.attr("x2", function(d) { return 100 })
.attr("y2", function(d) { return 100 })

Updating D3 circle pack layout

I'm trying to dynamically update a d3 circle pack layout with data I receive in json. Every second I call d3.json() to get the new json. Instead of updating the existing visualization, my implementation just creates a new one under the old one. I want to to dynamically update the existing layout instead...
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="d3.v2.js">
</script>
<script type="text/javascript" src="jquery-1.4.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="syntax.css" type="text/css">
<link rel="stylesheet" href="pack.css" type="text/css">
</head>
<body>
<div id="chart"> </div>
<script type="text/javascript">
var width = 960,
height = 960,
format = d3.format(",d");
var pack = d3.layout.pack()
.size([width - 4, height -4])
.value(function(d) { return d.size; });
var vis = null;
var node = null;
vis = d3.select("#chart").append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "pack");
/* vis.append("g")
.attr("transform", "translate(2, 2)"); */
function update(json){
// Creating the circle packed core
var gNodes = vis.data([json]).selectAll("g.node")
.data(pack.nodes);
//remove old data
gNodes.exit().remove();
}
setInterval(function(){
d3.json("http://10.0.1.4:8080/cluster", function(json) {
update(json);
//update the visualization
vis
.selectAll("circle")
.data([json]).selectAll("g.node")
.data(pack.nodes)
.attr("class", function(d) { return d.children ? "node" : "leaf node"; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.transition()
.duration(500)
.attr("r", function(d) { return d.children ? coreSize : d.r; });
var node = gNodes
.enter().append("g")
.attr("class", function(d) { return d.children ? "node" : "leaf node"; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
node.append("title")
.text(function(d) { return (d==null? "": d.name + (d.children ? "" : ": " + format(d.size))); });
node.append("circle")
.attr("r", function(d) { return (d==null? 0: d.r); });
node.filter(function(d) { return (d==null? "" : !d.children); }).append("text")
.attr("text-anchor", "middle")
.attr("dy", ".3em")
.text(function(d) { return (d==null?"":d.name.substring(0, d.r / 3)); });
});
}, 1000);
</script>
Take a look at my example here.
Basically, there is code for initial load, where all circles, tooltips, etc. are created and positioned in initial places. As well, the layout (pack) is created.
Than, on each button press, new data is loaded into pack, and the pack is recalculated. That crucial code is here:
if (dataSource == 0)
pack.value(function(d) { return d.size; });
if (dataSource == 1)
pack.value(function(d) { return 100; });
if (dataSource == 2)
pack.value(function(d) { return 1 +
Math.floor(Math.random()*501); });
var data1 = pack.nodes(data);
( I have three buttons, thats why 3 ifs)
After that, elements are tranistioned to new positions, and its attributes are changed as you determine.
Here are some pics with transition in action:
Start:
Transition:
End:

Categories