Good ...
I am using this example from the following url (http://bl.ocks.org/mbostock/7607535
):
My problem is that when inserting many circles, the main circle is not filled correctly as a kind of exaltation is created, my boss wants princial fills the circle.
I leave the code and a screenshot!
var margin = 10,
outerDiameter = 1000,
innerDiameter = outerDiameter - margin - margin;
var x = d3.scale.linear()
.range([0, innerDiameter]);
var y = d3.scale.linear()
.range([0, innerDiameter]);
var color = d3.scale.linear()
.domain([-1, 5])
.range(["hsl(152,80%,80%)", "hsl(228,30%,40%)"])
.interpolate(d3.interpolateHcl);
var pack = d3.layout.pack()
.padding(0.5)
.size([innerDiameter, innerDiameter])
.value(function(d) { return d.size; })
var svg = d3.select("#chart4").append("svg")
.attr("width", outerDiameter)
.attr("height", outerDiameter)
.append("g")
.attr("transform", "translate(" + margin + "," + margin + ")");
nodes = pack.nodes(testHeatMap);
svg.append("g").selectAll("circle")
.data(nodes)
.enter().append("circle")
//.attr("class", function(d) { return d.parent ? d.children ? "node" : "node node--leaf" : "node node--root"; })
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("r", function(d) { return d.r; })
.style("fill", function(d,i){
if(d.color)
return d.color
else if(d.children[0].color)
return d.children[0].color
else return d.children[0].children[i].color
})
.style("fill-opacity", "0.25")
.style("stroke", function (){ return "rgb(31, 119, 180)"})
.style("stroke-width", "1px")
d3.select(self.frameElement).style("height", outerDiameter + "px");
Related
I have created a force directed graph using d3.js. When new nodes are inserted to the graph, the graph starts moving on the white area as shown in this image. I would like to pinpoint the nodes (incoming and "old) dynamically in order to avoid problems of "cutting" some nodes of the viewBox, as shown in the image attached.
Any help?
My code so far is:
var w = 550;//1200,
h = 400;//750;
var zoom = d3.behavior.zoom()
.scaleExtent([0.1, 10])
.on("zoom", zoomed);
function zoomed() {
container.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
var testnode=[];
var color = d3.scale.category20();
var scale = 1200;
var vis = d3.select("#force")
.append("svg")
.attr("width", w) //w
.attr("height", h) //h
.attr("id", "svg")
.attr("group", "svg")
.attr("pointer-events", "all")
.attr("viewBox", "0 0 " + w + " " + h)
.call(zoom)
.attr("perserveAspectRatio", "xMinYMid meet")
.append('svg:g');
var force = d3.layout.force();
var nodes = force.nodes(),
links = force.links();
var update = function () {
var packetsReceivedArray = []
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 1e-6);
var link = vis.selectAll("line")
.data(links, function (d) {
return d.source.id + "-" + d.target.id;
});
var scale = d3.scale.linear()
.domain(d3.extent(links, function(d, i) {
return d.value;
}))
.range([1, 5]);
var scaleNode = d3.scale.linear()
.domain(d3.extent(nodes, function(d, i) {
return d.packetsReceived;
}))
.range([4, 16]);
link.enter().append("line")
.attr("id", function (d) {
return d.source.id + "-" + d.target.id;
})
.style("stroke-width", function(d) {
return scale(d.value) + "px";
})
.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("x", 10)
.attr("y", ".31em")
.attr("class", "nodeStrokeClass")
.attr("data-legend",function(d) {
if(d.group == 0){
return 'Basic Node'
}
return 'Other nodes'
});
nodeEnter.append("svg:text")
.attr("class", "textClass")
.attr("x", 14)
.attr("y", ".31em")
legend = vis.append("g")
.attr("class","legend")
.attr("transform","translate(900,30)")
.style("font-size","14px")
.call(d3.legend)
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;
});
});
force
.gravity(.1)
.charge(-300)
.friction(0.15)
.linkDistance(60)
.size([w - 150, h - 150])
.start();
};
I have a scatter plot with D3 and I'm trying to add circles to a selection based on changing data. I'm passing the data selection down to two functions: render and update. The render function is the initial render and update has the enter() and exit() methods. I can easily add the initial data set and get the circles no longer in the data set to exit. I'm using d.id as the d3 placeholder.
The problem: when I try to enter() the added data points, nothing happens. I've checked the length of the new data selection, and it's larger than the pre-existing. On the DOM, the smaller data set remains (the circles that were already there), but no new circles enter, even though the data set has changed.
I've looked through lots of tutorials regarding data joins, and I think I've appropriately called my enter() and exit() methods. What gives?
Here is my code:
var container = angular.element(document.querySelector('.chart-container'))[0];
var margin = {
top: container.clientHeight / 12,
right: container.clientWidth / 14,
bottom: container.clientHeight / 10,
left: container.clientWidth / 11
};
var w = container.clientWidth - margin.left - margin.right;
var h = container.clientHeight - margin.top - margin.bottom;
// ******** **************** ******** //
// ******** INITIAL RENDER ******** //
function render(input) {
console.log(Object.keys(input).length);
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 15]);
// *********** //
// SVG ELEMENT //
var svg = d3.select('.chart-container')
.append('svg')
.attr('class', 'scatter')
.attr('viewBox', '0, 0, ' + Math.round(w + margin.left + margin.right) + ', ' + Math.round(h + margin.top + margin.bottom))
.attr('preserveAspectRatio', 'xMinYMin')
// used to center element and make use of margins
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// add circles in group
var circles = svg.append('g')
.attr('class','circles')
.attr('clip-path','url(#chart-area)');
// add individual circles
var circle = circles.selectAll('circle')
.data(input, function(d) {return d.id;})
.enter()
.append('circle')
.attr('class', 'circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); })
.attr('fill', function(d, i) { return d["effective"]; })
.on('mouseover', function(d) {
tooltip.style('visibility', 'visible');
return tooltip.text(d["technology"]);
})
.on("mousemove", function(){ return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
// append clip path
svg.append('clipPath')
.attr('id','chart-area')
.append('rect')
.attr('class', 'rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', w)
.attr('height', h);
};
// ******** **************** ******** //
// ******** UPDATE ******** //
function update(updateObject) {
var input = updateObject;
var xScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ctc"]; })])
.range([0, w])
.nice();
var yScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["ttc"]; })])
.range([h, 0])
.nice();
var rScale = d3.scale.linear()
.domain([0, d3.max(input, function(d) { return d["effective"]; })])
.range([2, 15]);
var svg = d3.select('svg')
.data(input)
.attr('viewBox', '0, 0, ' + Math.round(w + margin.left + margin.right) + ', ' + Math.round(h + margin.top + margin.bottom))
.attr('preserveAspectRatio', 'xMinYMin')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// BIND TO DATA
var circles = d3.selectAll('circle')
.data(input, function(d) { return d.id; });
// Circles Enter
circles.enter()
.insert('svg:circle')
.attr('class', 'circle')
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
/*
.on('mouseover', function(d) {
tooltip.style('visibility', 'visible');
return tooltip.text(d["technology"]);
})
.on("mousemove", function(){ return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
*/
// UPDATE
circles.transition()
.duration(1000)
.attr('cx', function(d) { return xScale(d["ctc"]); })
.attr('cy', function(d) { return yScale(d["ttc"]); })
.attr('r', function(d) { return rScale(d["effective"]); });
// EXIT
circles.exit()
.transition()
.duration(500)
.attr('r', 0)
.style('opacity', 0)
.style('fill', 'gray')
.remove();
}
Update
here is a codepen for testing: http://codepen.io/himmel/pen/JdNJMM
The problem with the code is, that you are trying to use an object as data. d3.selection.data() takes an array, not an object. See the d3 wiki for more information on the data() function.
I have created an updated version of your codepen. I changed the data to an array and applied the correct conventional margin. Moreover I simplified the code by removing the double initialization of scales and the svg element.
I am trying to make my tree have a straight links between the parent node and the children nodes.
I have straight links now but the links are not connecting to the right places.
I think this may be because there is a transformation of rotation and translate to the nodes and the x and y didn't change somehow.
I have tried following the answer in this question but result is the same. D3: Substituting d3.svg.diagonal() with d3.svg.line()
var lines = svg.selectAll('line')
.data(links)
.enter()
.append('line')
.attr('stroke','#000')
lines.attr('x1',function(d){return d.source.x })
.attr('y1',function(d){return d.source.x})
.attr('x2',function(d){return d.target.x })
.attr('y2',function(d){return d.target.y })
Here is the full code:
var diameter = 1000;
var tree = d3.layout.tree()
.size([360, diameter / 2 - 100])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
// var diagonal = d3.svg.diagonal.radial()
// .projection(function(d) {
// return [d.y, d.x ]; })
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter )
.append("g")
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
d3.json("flare.json", function(error, root) {
var nodes = tree.nodes(root),
links = tree.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
var lines = svg.selectAll('line')
.data(links)
.enter()
.append('line')
.attr('stroke','#000')
lines.attr('x1',function(d){return d.source.x })
.attr('y1',function(d){return d.source.x})
.attr('x2',function(d){return d.target.x })
.attr('y2',function(d){return d.target.y })
var node = svg.selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d) { return "rotate(" + (d.x - 90 ) + ")translate(" + d.y + ")"; })
node.append("circle")
.attr("r", 10);
node.append("text")
.attr("dy", ".81em")
.attr("text-anchor", function(d) {
return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) { return d.x < 180 ? "translate(20)" : "rotate(180)translate(-20)"; })
.text(function(d) { return d.name; });
});
d3.select(self.frameElement).style("height", diameter - 150 + "px");
screenshots
I finally got it to work.. The solution is quite bizarre.
There is no projection method for line as there is for diagonal.
So when resetting the positions of x1,x2,y1,y2 needs a little bit tuning just like the diagonal projection.
Also I have to apply the transformation like how the nodes are applied but without the translation.
var link = svg.selectAll("link")
.data(links)
.enter().append("path")
.attr("class", "link")
var lines = svg.selectAll('line')
.data(links)
.enter()
.append('line')
.attr('stroke','#000')
lines.attr('x1',function(d){return d.source.y})
.attr('y1',function(d){return d.source.x/180*Math.PI})
.attr('x2',function(d){return d.target.y })
.attr('y2',function(d){return d.target.x/180*Math.PI})
// lines.attr("transform", function(d) {
// return "rotate(" + (d.source.x - 90 ) + ")translate(" + d.source.y + ")"; })
lines.attr("transform", function(d) {
return "rotate(" + (d.target.x - 90 ) + ")"; })
I created a bar plot and my Y axis is reversed somehow (also seems like the scale is not right). I really couldn't figure it out by myself. Here is the link for Jsfiddle.
This is the code I am working on, in case you want to try it elsewhere.
var w = 700;
var h = 400;
var margin = 40;
var dataset = [
{key:1,value:4000},
{key:2,value:3500},
{key:3,value:4400},
{key:4,value:3250},
{key:5,value:4785},
{key:6,value:3600},
{key:7,value:3200}
];
var key = function(d) {
return d.key;
};
var value = function(d) {
return d.value;
};
console.log(dataset);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset.length+1))
.rangeRoundBands([40, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, 5000])
.range([0, h-40]);
var x_axis = d3.svg.axis().scale(xScale);
var y_axis = d3.svg.axis().scale(yScale).orient("left");
d3.select("svg")
.append("g")
.attr("class","x axis")
.attr("transform","translate(0,"+(h-margin)+")")
.call(x_axis);
d3.select("svg")
.append("g")
.attr("class","y axis")
.attr("transform","translate("+margin+",0)")
.call(y_axis);
//Create bars
svg.selectAll("rect")
.data(dataset, key)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d.value);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d.value)-margin;
})
.attr("fill", function(d) {
return "rgb(96, 0, " + (d.value * 10) + ")";
})
//Tooltip
.on("mouseover", function(d) {
//Get this bar's x/y values, then augment for the tooltip
var xPosition = parseFloat(d3.select(this).attr("x")) + xScale.rangeBand() / 2;
var yPosition = parseFloat(d3.select(this).attr("y")) + 14;
//Update Tooltip Position & value
d3.select("#tooltip")
.style("left", xPosition + "px")
.style("top", yPosition + "px")
.select("#value")
.text(d.value);
d3.select("#tooltip").classed("hidden", false)
})
.on("mouseout", function() {
//Remove the tooltip
d3.select("#tooltip").classed("hidden", true);
}) ;
//Create labels
svg.selectAll("text")
.data(dataset, key)
.enter()
.append("text")
.text(function(d) {
return d.value;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d.value) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
Maybe this will help.
http://jsfiddle.net/S575k/4/
A few notes:
I reversed your y domain range from .range([0, h-margin]); to .range([h-margin, 0]); This will fix the issue of the y-axis marks going in the wrong direction because the browser consider's the origin (0,0) point to the the upper-left corner, and not the bottom-left corner like in math.
Because of this reversal I had to tweak your .attr('height') and .attr('y').
A nice way to find the height of bar in a bar chart is to realize that the yscale(0) will give you the pixel-position of the bottom of the barchart. You can then do yscale(value) - yscale(0) to get the pixel-height of your bars.
I am trying to implement the zooming feature on a dendrogram in the simplest, most basic way and have gotten it to work. The only issue is that the zoom event only works when the cursor is over an edge, a node, or text. How do I allow zooming when the cursor is on any portion of the svg?
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 2000 - margin.right - margin.left,
height = 2000 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, width])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, height])
.range([height, 0]);
var tree = d3.layout.tree()
.size([height, width])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
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 + ")")
.attr("pointer-events", "all")
.append('svg:g')
.call(d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1,8])
.on("zoom", zoom))
.append('svg:g');
function zoom(d) {
svg.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
d3.json("flare.json", function(error, root) {
var nodes = tree.nodes(root),
links = tree.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
// .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
node.append("circle")
.attr("r", 4.5);
node.append("text")
.attr("dy", ".31em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
// .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })
.text(function(d) { return d.name; });
});
d3.select(self.frameElement).style("height", "800px");
I have been using the following jsfiddle as a guide and cannot see where the difference is: http://jsfiddle.net/nrabinowitz/QMKm3/
Thanks in advance.
the jsfiddle you point to in your question has this...
vis.append('svg:rect')
.attr('width', w)
.attr('height', h)
.attr('fill', 'white');
This makes sure there's always something drawn no matter where you are. You need to adjust your code accordingly. You can make it opacity 0 if you don't like white and then you won't see it, but it does need to be there.