Fitting a d3.js Map to a container - javascript

I currently have a d3.js map of the world using the world-50m.json however I am having problems fitting the entire map into a container.
Here is a picture of what the problem is:
My Code:
d3.json("libraries/world-50m.json", function(error, world) {
var mapRatio = .5;
var width = 1600;
var height = 800;
var svg = d3.select("div#chart svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", "0 0 " + Math.min(width, height) + " " + Math.min(width, height));
var projection = d3.geo.equirectangular()
.scale(height / Math.PI)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule();
if (error) {
return console.error(error);
}
svg.append("g")
.attr("height", height)
.attr("width", width)
.attr("class", "land")
.selectAll("path")
.data([topojson.object(world, world.objects.land)])
.enter().append("path")
.attr("d", path);
svg.append("g")
.attr("height", height)
.attr("width", width)
.attr("class", "boundary")
.selectAll("boundary")
.data([topojson.object(world, world.objects.countries)])
.enter().append("path")
.attr("d", path);
svg.append("g")
.attr("class", "graticule")
.selectAll("path")
.data(graticule.lines)
.enter().append("path")
.attr("d", path);
var svg = d3.select("#chart svg").append("g");
var serverVerticesURL = JSON_URL;
var coordinateData = $.getJSON(
serverVerticesURL,
function (data, status) {
if (status === "success") {
// No error detected,
var vertexJSON = data;
var coordinates = [];
// Check that we have data to map.
if (vertexJSON.length > 0) {
// Plot points on map...
vertexJSON.forEach(function(column)
{
var value = column.location;
var origin = column.vertex;
var col1 = "Longitude";
var col2 = "Latitude";
var atkLong = value.match(/(.*)~.*/);
var atkLat = value.match(/.*~(.*)/);
coordinates.push([atkLong[1], atkLat[1], origin]);
});
if (typeof data.message === "string") {
vertexJSON = [];
}
var atkNodeSelection = svg.selectAll("circle");
var honeypotNode = svg.selectAll("circle");
// Appending attack nodes
var atkNode = atkNodeSelection.data(coordinates)
.enter().append("svg:circle")
.attr("class", "atkNode")
.attr("r", 5)
.attr("cx", function(d) { return projection([parseFloat(d[0]), parseFloat(d[1])])[0]; })
.attr("cy", function(d) { return projection([parseFloat(d[0]), parseFloat(d[1])])[1]; });
// Appending honeypot node
var hpnode = honeypotNode.data([[-73.934543,41.722841]])
.enter().append("svg:circle")
.attr("class", "honeypot")
.attr("r", 7)
.attr("cx", function(d) { return projection([d[0], d[1]])[0]; })
.attr("cy", function(d) { return projection([d[0], d[1]])[1]; });
var link = svg.selectAll(".link").data(coordinates).enter().append("line").attr("class", "link")
.attr("x1", function(d) { return projection([parseFloat(d[0]), parseFloat(d[1])])[0]; })
.attr("y1", function(d) { return projection([parseFloat(d[0]), parseFloat(d[1])])[1]; })
.attr("x2", function(d) { return projection([-73.934543,41.722841])[0]; })
.attr("y2", function(d) { return projection([-73.934543,41.722841])[1]; })
.attr("d", function (d) {
var x1 = projection([parseFloat(d[0]), parseFloat(d[1])])[0],
y1 = projection([parseFloat(d[0]), parseFloat(d[1])])[1],
x2 = projection([-73.934543,41.722841])[0],
y2 = projection([-73.934543,41.722841])[1],
// Defaults for normal edge.
drx = 0,
dry = 0,
xRotation = 0, // degrees
largeArc = 0, // 1 or 0
sweep = 1; // 1 or 0
return "M" + x1 + "," + y1 + "A" + drx + "," + dry + " " + xRotation + "," + largeArc + "," + sweep + " " + x2 + "," + y2;
});
Structure of the container:
<div id="#chart">
<svg>
<g class="land | boundary | graticule">
</g>
</svg>
</div>
css:
/*==================================================
* Map
* ===============================================*/
.graticule {
fill: #3385ff;
fill-opacity: .3;
stroke: #777;
stroke-width: 0.5px;
stroke-opacity: 0.5;
}
.land {
fill: #d0d0e1;
margin-left: 0px;
}
.boundary {
fill: none;
stroke: #0066ff;
stroke-width: 0.5px;
}
/*==================================================
* Attack Nodes
* ===============================================*/
.atkNode {
fill: red;
shape-rendering: auto;
fill-opacity: .7;
stroke-opacity: .8;
z-index: 2002;
}
.atkNode:hover {
fill: #0039e6;
fill-opacity: .5;
}

Related

How to create a grouped bars brushable chart with D3 js

I am creating a brushable bar chart, in the Y axis I need to have grouped chart with brushable content, whenever I am moving the brush, the graph is not getting refreshing.
Used the below code for creating the additional bar,
var bar2 = bar.enter().append("rect")
.attr("class", "bar2")
.attr("id","lesser")
.style("fill", "#ff7f0e")
.attr("y", function(d,i) { return main_yScale(d.country); })
.attr("height", main_yScale.rangeBand()/2)
.attr("x", 0)
.transition().duration(50)
.attr("width", function(d) { return main_xScale(d.result); });
I have tried in http://jsfiddle.net/mouneshp777/7xp10awb/1/
I am not able to fix the issue.
Thanks in Advance
The main problem is the way you use the join-pattern (selectAll("abc").data(mylist).enter()). Read the docs again to see the details.
why create a zoom when you don't use it. I have removed it from the example
every thing regarding tool tips is commented
do not calculate a new domain for X on each brush move, it gives the impression that the values change because the bar changes size.
don't define multiple elements with the same id (greater / lesser). Use a class.
define the fill with an attribute or with a style but not both and using different colors makes it even harder to determine which color you want/will be used.
why animate the width - 50ms is so short nobody will notice
what is the use of scroll()?
maybe an idea to port the chart over to d3v5
var data = [], svg, defs,gBrush, brush, main_xScale, mini_xScale, main_yScale,
mini_yScale,main_yZoom, main_xAxis, main_yAxis, mini_width, textScale;
init();
function init() {
for (var i = 1; i < 30; i++) {
var my_object = {};
my_object.key = i;
my_object.country = "Label"+i;
my_object.gtLabel = "greater";
my_object.value = Math.floor(Math.random() * 600);
my_object.ltLabel = "Lesser";
my_object.result = Math.floor(Math.random() * 300);
data.push(my_object);
}
// var zoomer = d3.behavior.zoom()
// .on("zoom", null);
var main_margin = {top: 10, right: 10, bottom: 30, left: 100},
main_width = 450 - main_margin.left - main_margin.right,
main_height = 250 - main_margin.top - main_margin.bottom;
var mini_margin = {top: 10, right: 10, bottom: 30, left: 10},
mini_height = 250 - mini_margin.top - mini_margin.bottom;
mini_width = 100 - mini_margin.left - mini_margin.right;
svg = d3.select("body").append("svg")
.attr("class", "svgWrapper")
.attr("width", main_width + main_margin.left + main_margin.right + mini_width + mini_margin.left + mini_margin.right)
.attr("height", main_height + main_margin.top + main_margin.bottom);
// .call(zoomer)
// .on("wheel.zoom", scroll)
// .on("mousedown.zoom", null)
// .on("touchstart.zoom", null)
// .on("touchmove.zoom", null)
// .on("touchend.zoom", null);
var mainGroup = svg.append("g")
.attr("class","mainGroupWrapper")
.attr("transform","translate(180,10)")
.append("g")
.attr("clip-path", "url(#clip)")
.style("clip-path", "url(#clip)")
.attr("class","mainGroup");
var miniGroup = svg.append("g")
.attr("class","miniGroup")
.attr("transform","translate(135,10)");
var brushGroup = svg.append("g")
.attr("class","brushGroup")
.attr("transform","translate(135,10)");
main_xScale = d3.scale.linear().range([0, main_width]);
mini_xScale = d3.scale.linear().range([0, mini_width]);
main_yScale = d3.scale.ordinal().rangeBands([0, main_height], 0.4, 0);
mini_yScale = d3.scale.ordinal().rangeBands([0, mini_height], 0.4, 0);
main_yZoom = d3.scale.linear()
.range([0, main_height])
.domain([0, main_height]);
main_xAxis = d3.svg.axis()
.scale(main_xScale)
.orient("bottom")
.tickFormat(d3.format(".2s"));
d3.select(".mainGroupWrapper")
.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + 0 + "," + (main_height + 5) + ")");
svg.append("text")
.attr("transform", "translate(" + (main_width / 2) + " ," + (main_height + (main_margin.bottom -60) ) +")")
.attr("dy", ".71em")
.attr("class", "x axis")
.attr("stroke-width",1)
.style("font-size","15px")
.text("");
main_yAxis = d3.svg.axis()
.scale(main_yScale)
.orient("left").tickSize(5);
mainGroup.append("g")
.attr("class", "y axis")
.attr("transform", "translate(-48,0)");
main_xScale.domain([0, d3.max(data, function(d) { return d.value; })]);
mini_xScale.domain([0, d3.max(data, function(d) { return d.value; })]);
main_yScale.domain(data.map(function(d) { return d.country; }));
mini_yScale.domain(data.map(function(d) { return d.country; }));
d3.select(".mainGroup").select(".y.axis").call(main_yAxis);
textScale = d3.scale.linear()
.domain([25,50])
.range([12,6])
.clamp(true);
var brushExtent = 15;// Math.max( 1, Math.min( 20, Math.round(data.length*0.2)));
brush = d3.svg.brush()
.y(mini_yScale)
.extent([mini_yScale(data[0].country), mini_yScale(data[brushExtent].country)])
.on("brush", brushmove);
gBrush = d3.select(".brushGroup").append("g")
.attr("class", "brush")
.call(brush);
gBrush.selectAll(".resize")
.append("line")
.attr("x2", 40);
gBrush.selectAll("rect")
.attr("width", 40);
gBrush.select(".background")
.on("mousedown.brush", brushcenter)
.on("touchstart.brush", brushcenter);
defs = svg.append("defs")
defs.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", -main_margin.left)
.attr("width", main_width + main_margin.left)
.attr("height", main_height);
var mini_bar = d3.select(".miniGroup").selectAll(".bar")
.data(data, function(d) { return d.key; });
mini_bar
.attr("width", function(d) { return (mini_xScale(d.value)/2.2); })
.attr("y", function(d,i) { return mini_yScale(d.country); })
.attr("height", mini_yScale.rangeBand());
mini_bar.enter().append("rect")
.attr("class", "bar")
.attr("x", 0)
.attr("width", function(d) { return mini_xScale(d.value/2.2); })
.attr("y", function(d,i) { return mini_yScale(d.country); })
.attr("height", mini_yScale.rangeBand())
.style("fill", "url(#gradient-rainbow-mini)");
mini_bar.exit()
.remove();
gBrush.call(brush.event);
}
function update() {
// var divTooltip = svg.append("div").attr("class", "toolTip");
if (d3.select(".mainGroup").select(".bar2.greater").empty()) {
var bar = d3.select(".mainGroup").selectAll(null)
.data(data, function(d) { return d.key; });
bar.enter().append("rect")
.attr("class", "bar2 greater")
.attr("fill", "#1f77b4")
.attr("x", 0);
bar.enter().append("rect")
.attr("class", "bar2 lesser")
.attr("fill", "#ff7f0e")
.attr("x", 0);
}
d3.selectAll(".bar2.greater")
.attr("y", function(d) { return main_yScale(d.country) + main_yScale.rangeBand()/2; })
.attr("width", function(d) { return main_xScale(d.value); })
.attr("height", main_yScale.rangeBand()/2);
d3.selectAll(".bar2.lesser")
.attr("y", function(d,i) { return main_yScale(d.country); })
.attr("width", function(d) { return main_xScale(d.result); })
.attr("height", main_yScale.rangeBand()/2);
// bar
// .attr("y", function(d,i) { return main_yScale(d.country); })
// .attr("height", main_yScale.rangeBand())
// .attr("x", 0)
// .transition().duration(50)
// .attr("width", function(d) { return main_xScale(d.value); });
// var bar1= bar.enter().append("rect")
// .attr("class", "bar2")
// // .attr("id","greater")
// // .style("fill", "#1f77b4")
// // .attr("fill", function(d,i) { return "#000" })
// .attr("fill", "#1f77b4")
// .attr("y", function(d,i) { return main_yScale(d.country) + main_yScale.rangeBand()/2; })
// .attr("height", main_yScale.rangeBand()/2)
// .attr("x", 0)
// .transition().duration(50)
// .attr("width", function(d) { return main_xScale(d.value); });
// // console.log(bar1);
// var bar2 = bar.enter().append("rect")
// .attr("class", "bar2")
// // .attr("id","lesser")
// // .style("fill", "#ff7f0e")
// .attr("fill", "#ff7f0e")
// .attr("y", function(d,i) { return main_yScale(d.country); })
// .attr("height", main_yScale.rangeBand()/2)
// .attr("x", 0)
// .transition().duration(50)
// .attr("width", function(d) { return main_xScale(d.result); });
// console.log(bar2);
// var dwellTimeSecsEntered = $("#dwellTimeSecs").val();
// var lessValue = "value";
// var greaterValues = "result";
// var tip = d3.tip()
// .attr('class', 'd3-tip')
// .offset([10, 75])
// .html(function(d) {
// return "<strong>"+d.country+ " </strong><br>" +
// ""+lessValue+" :<span style='color:black'>" + d.result + "</span><br>"+greaterValues+": <span style='color:black'>" + d.value + "</span><br>";
// });
// bar.on('mouseover', tip.show)
// .on('mouseout', tip.hide);
// svg.call(tip);
// bar.exit()
// .remove();
}
function brushmove() {
var extent = brush.extent();
var selected = mini_yScale.domain()
.filter(function(d) { return (extent[0] - mini_yScale.rangeBand() + 1e-2 <= mini_yScale(d)) && (mini_yScale(d) <= extent[1] - 1e-2); });
d3.select(".miniGroup").selectAll(".bar")
.style("fill", "lightGrey");
d3.selectAll(".y.axis text")
.style("font-size", textScale(selected.length));
var originalRange = main_yZoom.range();
main_yZoom.domain( extent );
main_yScale.domain(data.map(function(d) { return d.country; }));
main_yScale.rangeBands( [ main_yZoom(originalRange[0]), main_yZoom(originalRange[1]) ], 0.4, 0);
d3.select(".mainGroup")
.select(".y.axis")
.call(main_yAxis);
// keep x-axis at the same scale independet of selected brush range
// var newMaxXScale = d3.max(data, function(d) { return selected.indexOf(d.country) > -1 ? d.value : 0; });
// main_xScale.domain([0, newMaxXScale]);
// can be moved to the init() call
d3.select(".mainGroupWrapper")
.select(".x.axis")
.transition().duration(50)
.call(main_xAxis);
update();
}
function brushcenter() {
var target = d3.event.target,
extent = brush.extent(),
size = extent[1] - extent[0],
range = mini_yScale.range(),
y0 = d3.min(range) + size / 2,
y1 = d3.max(range) + mini_yScale.rangeBand() - size / 2,
center = Math.max( y0, Math.min( y1, d3.mouse(target)[1] ) );
d3.event.stopPropagation();
gBrush
.call(brush.extent([center - size / 2, center + size / 2]))
.call(brush.event);
}
function scroll() {
var extent = brush.extent(),
size = extent[1] - extent[0],
range = mini_yScale.range(),
y0 = d3.min(range),
y1 = d3.max(range) + mini_yScale.rangeBand(),
dy = d3.event.deltaY,
topSection;
if ( extent[0] - dy < y0 ) { topSection = y0; }
else if ( extent[1] - dy > y1 ) { topSection = y1 - size; }
else { topSection = extent[0] - dy; }
d3.event.stopPropagation();
d3.event.preventDefault();
gBrush
.call(brush.extent([ topSection, topSection + size ]))
.call(brush.event);
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: block;
}
body {
font-size: 10px;
font-family: 'Open Sans', sans-serif;
font-weight: 400;
text-align: center;
}
#title {
font-size: 20px;
padding-bottom: 10px;
padding-top: 20px;
font-weight: 300;
}
#explanation {
font-size: 12px;
max-width: 620px;
margin: 0 auto;
padding-top: 10px;
color: #ababab;
font-weight: 300;
}
.brush .extent {
fill-opacity: .125;
shape-rendering: crispEdges;
}
.resize {
display: inline !important; /* show when empty */
fill: #7A7A7A;
fill-opacity: 1;
stroke: #7A7A7A;
stroke-width: 2px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<body>
</body>

Getting the node details in the context menu in D3

I am trying to get the node details (id attribute) when it is right clicked and the contextmenu function is called. I am able to get the node object using var self = d3.select(this); but I am not able to work out the
id attribute of the node (i can see it in the console log though)
I am planning to pass the id to the menu function once I'll get the node.id
JSFiddle
var circle = svg.append("g").selectAll("circle") .data(force.nodes())
.enter().append("circle").attr("r", 6) .call(force.drag)
.on('contextmenu', function(){
d3.event.preventDefault();
var self = d3.select(this);
console.log(self);
var n1=(self[0])[0];
console.log(n1);
menu(d3.mouse(svg.node())[0], d3.mouse(svg.node())[1]);
});
You can pass the datum as a parameter of the function called on the contextmenu event:
.on('contextmenu', function(d) { ... }
which allows you to get the id within the function:
console.log(d.id);
.node {
fill: #000;
}
.cursor {
fill: green;
stroke: brown;
pointer-events: none;
}
.node text {
pointer-events: none;
font: 10px sans-serif;
}
path.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
.link {
fill: none;
stroke: #666;
stroke-width: 1.5px;
}
#licensing {
fill: green;
}
.link.licensing {
stroke: green;
}
.link.resolved {
stroke-dasharray: 0,2 1;
}
circle {
fill: green;
stroke: red;
stroke-width: 1.5px;
}
text {
font: 10px sans-serif;
pointer-events: none;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var width = 500, height = 300;
var links = [{source:"simulator",target:"monitor" ,type:"resolved"} , {source:"web",target:"monitor" ,type:"resolved"} ];
var nodes = [ {"id":"monitor", "grp":"system"}, {"id":"simulator", "grp":"system"}, {id:"web", grp:"client"}];
function reset() {
}
function contextMenu() {
var height,
width,
margin = 0.1, // fraction of width
items = [],
rescale = false,
style = {
'rect': {
'mouseout': {
'fill': 'rgb(244,244,244)',
'stroke': 'white',
'stroke-width': '1px'
},
'mouseover': {
'fill': 'rgb(200,200,200)'
}
},
'text': {
'fill': 'steelblue',
'font-size': '13'
}
};
function menu(x, y) {
d3.select('.context-menu').remove();
scaleItems();
// Draw the menu
d3.select('svg')
.append('g').attr('class', 'context-menu')
.selectAll('tmp')
.data(items).enter()
.append('g').attr('class', 'menu-entry')
.style({'cursor': 'pointer'})
.on('mouseover', function(){
d3.select(this).select('rect').style(style.rect.mouseover) })
.on('mouseout', function(){
d3.select(this).select('rect').style(style.rect.mouseout) });
d3.selectAll('.menu-entry')
.append('rect')
.attr('x', x)
.attr('y', function(d, i){ return y + (i * height); })
.attr('width', width)
.attr('height', height)
.style(style.rect.mouseout);
d3.selectAll('.menu-entry')
.append('text')
.text(function(d){ return d; })
.attr('x', x)
.attr('y', function(d, i){ return y + (i * height); })
.attr('dy', height - margin / 2)
.attr('dx', margin)
.style(style.text);
// Other interactions
d3.select('body')
.on('click', function() {
d3.select('.context-menu').remove();
});
}
menu.items = function(e) {
if (!arguments.length) return items;
for (i in arguments) items.push(arguments[i]);
rescale = true;
return menu;
}
// Automatically set width, height, and margin;
function scaleItems() {
if (rescale) {
d3.select('svg').selectAll('tmp')
.data(items).enter()
.append('text')
.text(function(d){ return d; })
.style(style.text)
.attr('x', -1000)
.attr('y', -1000)
.attr('class', 'tmp');
var z = d3.selectAll('.tmp')[0]
.map(function(x){ return x.getBBox(); });
width = d3.max(z.map(function(x){ return x.width; }));
margin = margin * width;
width = width + 2 * margin;
height = d3.max(z.map(function(x){ return x.height + margin / 2; }));
// cleanup
d3.selectAll('.tmp').remove();
rescale = false;
}
}
return menu;
}
var width = 400,
height = 200,
radius = 8;
var map = {}
nodes.forEach(function(d,i){
map[d.id] = i;
})
links.forEach(function(d) {
d.source = map[d.source];
d.target = map[d.target];
})
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.linkDistance(50)
.charge(-200)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Per-type markers, as they don't inherit styles.
svg.append("defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("marker")
.attr("id", function(d) { return d; })
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("g").selectAll("path")
.data(force.links())
.enter().append("path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var menu = contextMenu().items('first item', 'second option', 'whatever, man');
var circle = svg.append("g").selectAll("circle")
.data(force.nodes())
.enter().append("circle")
.attr("r", 6)
.call(force.drag)
.on('contextmenu', function(d){
d3.event.preventDefault();
var self = d3.select(this);
var n1=(self[0])[0];
console.log(d.id);
menu(d3.mouse(svg.node())[0], d3.mouse(svg.node())[1]);
});
var text = svg.append("g").selectAll("text")
.data(force.nodes())
.enter().append("text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.id; });
var node = svg.selectAll(".node"),
link = svg.selectAll(".link");
function mousedownNode(d, i) {
nodes.splice(i, 1);
links = links.filter(function(l) {
return l.source !== d && l.target !== d;
});
d3.event.stopPropagation();
refresh();
}
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", linkArc);
circle.attr("transform", transform);
text.attr("transform", transform);
}
function linkArc(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
}
function transform(d) {
return "translate(" + d.x + "," + d.y + ")";
}
</script>
In addition: For all the ones that want to know how to be able to show node details (for example the node name) in the context menu itself - this is my solution.
The node details can be taken from the "data" element
The placeholder can be taken from the "d" element
The desired information to show in the context menu has to be written into the "text" attribute
if(d.title == 'ConfigMenuPlaceholder'){
text = 'Config: '+data.name;
}
These lines should be written at the following position:
function createNestedMenu(parent, root, depth = 0) {
var resolve = function (value) {
return utils.toFactory(value).call(root, data, index);
};
parent.selectAll('li')
.data(function (d) {
var baseData = depth === 0 ? menuItems : d.children;
return resolve(baseData);
})
.enter()
.append('li')
.each(function (d) {
var elm = this;
// get value of each data
var isDivider = !!resolve(d.divider);
var isDisabled = !!resolve(d.disabled);
var hasChildren = !!resolve(d.children);
var hasAction = !!d.action;
var text = isDivider ? '<hr>' : resolve(d.title);
if(d.title == 'ConfigMenuPlaceholder'){
text = 'Config: '+data.name;
}
var listItem = d3.select(this)
.classed('is-divider', isDivider)
.classed('is-disabled', isDisabled)
.classed('is-header', !hasChildren && !hasAction)
.classed('is-parent', hasChildren)
.html(text)
.on('click', function () {
// do nothing if disabled or no action
if (isDisabled || !hasAction) return;
d.action(elm, data, index);
//d.action.call(root, data, index);
closeMenu();
});
if (hasChildren) {
// create children(`next parent`) and call recursive
var children = listItem.append('ul').classed('is-children', true);
createNestedMenu(children, root, ++depth)
}
});
}

tooltip for a scatter plot matrix - using d3

I have a scatter plot matrix for which I need a tooltip. I tried using the following code, but then, it gives me tooltips at random points and not at the exact cells.
Can someone tell me where am I going wrong ? Or is not possible to generate a tooltip for my data?
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
padding: 10px;
}
.axis,
.frame {
shape-rendering: crispEdges;
}
.axis line {
stroke: #ddd;
}
.axis path {
display: none;
}
.frame {
fill: none;
stroke: #aaa;
}
circle {
fill-opacity: .7;
}
circle.hidden {
fill: #ccc !important;
}
.extent {
fill: #000;
fill-opacity: .125;
stroke: #fff;
}
</style>
<body>
<div id="chart3"> </div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>
var width = 419,
size = 130,
padding = 19.5,
height = 313;
var x = d3.scale.linear().domain([0,100])
.range([padding / 2, size - padding / 2]);
var y = d3.scale.linear().domain([0,1])
.range([size - padding / 2, padding / 2]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var color = d3.scale.ordinal()
.domain(['no chemo', 'induction', 'induction+chemoRT', 'concurrent'])
.range(['#ffae19', '#4ca64c', '#4682B4', '#c51b8a']);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([50,70])
.html(function (d) {
var coordinates = d3.mouse(this);
xValue = x.invert(coordinates[0]);
yValue = y.invert(coordinates[1]);
return "<strong> Age Of Patient " + d3.format(".2f")(xValue * 100)+
" <br/> Probability of Survival : " + d3.format(".2f")(yValue*100) + " % </strong>";
});
d3.csv("SurvivalProbability.csv", function (error, data) {
if (error)
throw error;
var domainByTrait = {},
traits = d3.keys(data[0]).filter(function (d) {
return (d == 'AgeAtTx' || d == 'Probability of Survival')
}),
n = traits.length;
traits.forEach(function (trait) {
domainByTrait[trait] = d3.extent(data, function (d) {
return d[trait];
});
});
xAxis.tickSize(size * n);
yAxis.tickSize(-size * n);
var brush = d3.svg.brush()
.x(x)
.y(y)
.on("brushstart", brushstart)
.on("brush", brushmove)
.on("brushend", brushend);
var svg = d3.select("#chart3").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + padding + "," + padding / 2 + ")");
svg.call(tip);
svg.selectAll(".x.axis")
.data(traits)
.enter().append("g")
.attr("class", "x axis")
.attr("transform", function (d, i) {
return "translate(" + (n - i - 1) * size + ",0)";
})
.each(function (d) {
x.domain(domainByTrait[d]);
d3.select(this).call(xAxis);
});
svg.selectAll(".y.axis")
.data(traits)
.enter().append("g")
.attr("class", "y axis")
.attr("transform", function (d, i) {
return "translate(0," + i * size + ")";
})
.each(function (d) {
y.domain(domainByTrait[d]);
d3.select(this).call(yAxis);
});
var cell = svg.selectAll(".cell")
.data(cross(traits, traits))
.enter().append("g")
.attr("class", "cell")
.attr("transform", function (d) {
return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")";
})
.each(plot)
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
// Titles for the diagonal.
cell.filter(function (d) {
return d.i === d.j;
}).append("text")
.attr("x", padding)
.attr("y", padding)
.attr("dy", ".71em")
.text(function (d) {
return d.x;
});
cell.call(brush);
function plot(p) {
var cell = d3.select(this);
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
cell.append("rect")
.attr("class", "frame")
.attr("x", padding / 2)
.attr("y", padding / 2)
.attr("width", size - padding)
.attr("height", size - padding);
cell.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function (d) {
return x(d[p.x]);
})
.attr("cy", function (d) {
return y(d[p.y]);
})
.attr("r", 5)
.style("fill", function (d) {
return color(d.Chemotherapy);
});
}
var brushCell;
// Clear the previously-active brush, if any.
function brushstart(p) {
if (brushCell !== this) {
d3.select(brushCell).call(brush.clear());
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
brushCell = this;
}
}
// Highlight the selected circles.
function brushmove(p) {
var e = brush.extent();
svg.selectAll("circle").classed("hidden", function (d) {
return e[0][0] > d[p.x] || d[p.x] > e[1][0]
|| e[0][1] > d[p.y] || d[p.y] > e[1][1];
});
}
// If the brush is empty, select all circles.
function brushend() {
if (brush.empty())
svg.selectAll(".hidden").classed("hidden", false);
}
function cross(a, b) {
var c = [], n = a.length, m = b.length, i, j;
for (i = - 1; ++i < n; )
for (j = - 1; ++j < m; )
c.push({x: a[i], i: i, y: b[j], j: j});
return c;
}
d3.select(self.frameElement).style("height", size * n + padding + 20 + "px");
var legendRectSize = 10;
var legendSpacing = 10;
var legend = svg.append("g")
.selectAll("g")
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function (d, i) {
var height = legendRectSize;
var x = 2 * size;
var y = (i * height) + 120;
return 'translate(' + x + ',' + y + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendSpacing)
.text(function (d) {
return d;
});
});
</script>
A screenshot of my data - Survival Probability.csv
Ethnicity,AgeAtTx,Site,Tcategory,Nodal_Disease,ecog,Chemotherapy,Local_Therapy,Probability of Survival,KM OS,OS (months),sex
white,65.93972603,supraglottic,T3,N+,0,no chemo,LP/RT alone,0.366190068,0,112.9,Female
white,69.42465753,supraglottic,T3,N+,0,induction,PLRT,0.396018836,0,24.1,Male
white,68.14246575,supraglottic,T3,N0,3,no chemo,LP/RT alone,0.439289384,0,3.566666667,Female
white,40.30410959,supraglottic,T3,N+,1,no chemo,LP/RT alone,0.512773973,1,226.3,Male
white,47.96438356,supraglottic,T3,N+,0,no chemo,PLRT,0.472208904,0,9.6,Female
white,70.3369863,supraglottic,T3,N+,0,no chemo,LP/RT alone,0.324965753,0,25.26666667,Male
white,60.50136986,supraglottic,T3,N+,2,no chemo,LP/RT alone,0.323424658,0,9.5,Female
white,60.72328767,supraglottic,T3,N+,1,no chemo,LP/RT alone,0.321344178,0,15.03333333,Male
white,59.36986301,supraglottic,T3,N0,1,induction,LP/chemoRT,0.646532534,0,4.5,Male
other,57.64931507,supraglottic,T3,N+,1,concurrent,LP/chemoRT,0.662662671,1,52.73333333,Male
This is an interesting situation. It boils down essentially to element append order and mouse-events. First, let's fix the obvious. You want a tooltip on each circle, so you shouldn't be calling tip.show when you mouse over a cell, but on the circles:
cell.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) {
return x(d[p.x]);
})
.attr("cy", function(d) {
return y(d[p.y]);
})
.attr("r", 5)
.style("fill", function(d) {
return color(d.Chemotherapy);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
But you'll notice with this change, we don't receive the events on our circles. This is because svg.brush is placing a rect over each cell so that you can select with the extent, and it's receiving the mouse events. So to fix that we change the order of drawing to brush then circle:
var cell = svg.selectAll(".cell")
.data(cross(traits, traits))
.enter().append("g")
.attr("class", "cell")
.attr("transform", function(d) {
return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")";
});
// add the brush stuff
cell.call(brush);
// now the circles
cell.each(plot);
But we still have a problem. We've got one more rect on top of our circles, the frame rect. Since we don't care about mouse events on it just do a simple:
.style("pointer-events", "none");
Putting this all together:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
padding: 10px;
}
.axis,
.frame {
shape-rendering: crispEdges;
}
.axis line {
stroke: #ddd;
}
.axis path {
display: none;
}
.frame {
fill: none;
stroke: #aaa;
}
circle {
fill-opacity: .7;
}
circle.hidden {
fill: #ccc !important;
}
.extent {
fill: #000;
fill-opacity: .125;
stroke: #fff;
}
</style>
<body>
<div id="chart3"> </div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>
var width = 419,
size = 130,
padding = 19.5,
height = 313;
var x = d3.scale.linear().domain([0, 100])
.range([padding / 2, size - padding / 2]);
var y = d3.scale.linear().domain([0, 1])
.range([size - padding / 2, padding / 2]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5);
var color = d3.scale.ordinal()
.domain(['no chemo', 'induction', 'induction+chemoRT', 'concurrent'])
.range(['#ffae19', '#4ca64c', '#4682B4', '#c51b8a']);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([50, 70])
.html(function(d) {
console.log(d)
var coordinates = d3.mouse(this);
xValue = x.invert(coordinates[0]);
yValue = y.invert(coordinates[1]);
return "<strong> Age Of Patient " + d3.format(".2f")(xValue * 100) +
" <br/> Probability of Survival : " + d3.format(".2f")(yValue * 100) + " % </strong>";
});
//d3.csv("data.csv", function(error, data) {
// if (error)
// throw error;
var data = [{"Ethnicity":"white","AgeAtTx":"65.93972603","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"0","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.366190068","KM OS":"0","OS (months)":"112.9","sex":"Female"},{"Ethnicity":"white","AgeAtTx":"69.42465753","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"0","Chemotherapy":"induction","Local_Therapy":"PLRT","Probability of Survival":"0.396018836","KM OS":"0","OS (months)":"24.1","sex":"Male"},{"Ethnicity":"white","AgeAtTx":"68.14246575","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N0","ecog":"3","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.439289384","KM OS":"0","OS (months)":"3.566666667","sex":"Female"},{"Ethnicity":"white","AgeAtTx":"40.30410959","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"1","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.512773973","KM OS":"1","OS (months)":"226.3","sex":"Male"},{"Ethnicity":"white","AgeAtTx":"47.96438356","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"0","Chemotherapy":"no chemo","Local_Therapy":"PLRT","Probability of Survival":"0.472208904","KM OS":"0","OS (months)":"9.6","sex":"Female"},{"Ethnicity":"white","AgeAtTx":"70.3369863","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"0","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.324965753","KM OS":"0","OS (months)":"25.26666667","sex":"Male"},{"Ethnicity":"white","AgeAtTx":"60.50136986","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"2","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.323424658","KM OS":"0","OS (months)":"9.5","sex":"Female"},{"Ethnicity":"white","AgeAtTx":"60.72328767","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"1","Chemotherapy":"no chemo","Local_Therapy":"LP/RT alone","Probability of Survival":"0.321344178","KM OS":"0","OS (months)":"15.03333333","sex":"Male"},{"Ethnicity":"white","AgeAtTx":"59.36986301","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N0","ecog":"1","Chemotherapy":"induction","Local_Therapy":"LP/chemoRT","Probability of Survival":"0.646532534","KM OS":"0","OS (months)":"4.5","sex":"Male"},{"Ethnicity":"other","AgeAtTx":"57.64931507","Site":"supraglottic","Tcategory":"T3","Nodal_Disease":"N+","ecog":"1","Chemotherapy":"concurrent","Local_Therapy":"LP/chemoRT","Probability of Survival":"0.662662671","KM OS":"1","OS (months)":"52.73333333","sex":"Male"}];
var domainByTrait = {},
traits = d3.keys(data[0]).filter(function(d) {
return (d == 'AgeAtTx' || d == 'Probability of Survival')
}),
n = traits.length;
traits.forEach(function(trait) {
domainByTrait[trait] = d3.extent(data, function(d) {
return d[trait];
});
});
xAxis.tickSize(size * n);
yAxis.tickSize(-size * n);
var brush = d3.svg.brush()
.x(x)
.y(y)
.on("brushstart", brushstart)
.on("brush", brushmove)
.on("brushend", brushend);
var svg = d3.select("#chart3").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + padding + "," + padding / 2 + ")");
svg.call(tip);
svg.selectAll(".x.axis")
.data(traits)
.enter().append("g")
.attr("class", "x axis")
.attr("transform", function(d, i) {
return "translate(" + (n - i - 1) * size + ",0)";
})
.each(function(d) {
x.domain(domainByTrait[d]);
d3.select(this).call(xAxis);
});
svg.selectAll(".y.axis")
.data(traits)
.enter().append("g")
.attr("class", "y axis")
.attr("transform", function(d, i) {
return "translate(0," + i * size + ")";
})
.each(function(d) {
y.domain(domainByTrait[d]);
d3.select(this).call(yAxis);
});
var cell = svg.selectAll(".cell")
.data(cross(traits, traits))
.enter().append("g")
.attr("class", "cell")
.attr("transform", function(d) {
return "translate(" + (n - d.i - 1) * size + "," + d.j * size + ")";
});
cell.call(brush);
cell.each(plot);
// Titles for the diagonal.
cell.filter(function(d) {
return d.i === d.j;
}).append("text")
.attr("x", padding)
.attr("y", padding)
.attr("dy", ".71em")
.text(function(d) {
return d.x;
});
function plot(p) {
var cell = d3.select(this);
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
cell.append("rect")
.attr("class", "frame")
.attr("x", padding / 2)
.attr("y", padding / 2)
.attr("width", size - padding)
.attr("height", size - padding)
.style("pointer-events", "none");
cell.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", function(d) {
return x(d[p.x]);
})
.attr("cy", function(d) {
return y(d[p.y]);
})
.attr("r", 5)
.style("fill", function(d) {
return color(d.Chemotherapy);
})
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
}
var brushCell;
// Clear the previously-active brush, if any.
function brushstart(p) {
if (brushCell !== this) {
d3.select(brushCell).call(brush.clear());
x.domain(domainByTrait[p.x]);
y.domain(domainByTrait[p.y]);
brushCell = this;
}
}
// Highlight the selected circles.
function brushmove(p) {
var e = brush.extent();
svg.selectAll("circle").classed("hidden", function(d) {
return e[0][0] > d[p.x] || d[p.x] > e[1][0] || e[0][1] > d[p.y] || d[p.y] > e[1][1];
});
}
// If the brush is empty, select all circles.
function brushend() {
if (brush.empty())
svg.selectAll(".hidden").classed("hidden", false);
}
function cross(a, b) {
var c = [],
n = a.length,
m = b.length,
i, j;
for (i = -1; ++i < n;)
for (j = -1; ++j < m;)
c.push({
x: a[i],
i: i,
y: b[j],
j: j
});
return c;
}
var legendRectSize = 10;
var legendSpacing = 10;
var legend = svg.append("g")
.selectAll("g")
.data(color.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr('transform', function(d, i) {
var height = legendRectSize;
var x = 2 * size;
var y = (i * height) + 120;
return 'translate(' + x + ',' + y + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendSpacing)
.text(function(d) {
return d;
});
//});
</script>

I need to draw a chord in d3 in eclipse shape rather as circle

Here is my sample js file i need to draw a chord but in eclipse shape rather then a circle. Secondly i need to know that what is a matrix use while creating chord diagram and are we able to draw a chord with simple json file (without using matrix) as mentioned http://www.delimited.io/blog/2013/12/8/chord-diagrams-in-d3 here. Because in every example of chord some matrix is give to draw it. I am new to d3 i need to learn lot of things. Can any one help really appreciate it
var outerRadius = 500 / 2,
innerRadius = outerRadius - 100;
var fill = d3.scale.category20c();
var chord = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.descending);
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(innerRadius + 20);
var svg = d3.select('#content').append("svg")
.attr("width", outerRadius * 2)
.attr("height", outerRadius * 2)
.append("g")
.attr("transform", "translate(" + outerRadius + "," + outerRadius +
")");
d3.json("readme.json", function(error, imports) {
if (error) throw error;
var indexByName = d3.map(),
nameByIndex = d3.map(),
matrix = [],
n = 0;
// Returns the Flare package name for the given class name.
function name(name) {
return name.substring(0, name.lastIndexOf(".")).substring(6);
}
// Compute a unique index for each package name.
imports.forEach(function(d) {
if (!indexByName.has(d = name(d.name))) {
nameByIndex.set(n, d);
indexByName.set(d, n++);
}
});
// Construct a square matrix counting package imports.
imports.forEach(function(d) {
var source = indexByName.get(name(d.name)),
row = matrix[source];
if (!row) {
row = matrix[source] = [];
for (var i = -1; ++i < n;) row[i] = 0;
}
d.imports.forEach(function(d) { row[indexByName.get(name(d))]++; });
});
chord.matrix(matrix);
var g = svg.selectAll("g.group")
.data(chord.groups())
.enter().append("svg:g")
.attr("class", "group")
.on("mouseover", fade(.02))
.on("mouseout", fade(.80));
// .on("mouseover", mouseover);
//.on("mouseout", fade(1));
g.append("svg:path")
.style("stroke", "none")
.style("fill", function(d) { return fill(d.index); })
.attr("d", arc);
/* g.append("path")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", arc);*/
g.append("text")
.each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2; })
.attr("dy", ".35em")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + (innerRadius + 26) + ")"
+ (d.angle > Math.PI ? "rotate(180)" : "");
})
.style("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
.text(function(d) { return nameByIndex.get(d.index); });
svg.selectAll(".chord")
.data(chord.chords)
.enter().append("path")
.attr("class", "chord")
.style("stroke", function(d) { return
d3.rgb(fill(d.source.index)).darker(); })
.style("fill", function(d) { return fill(d.source.index); })
//.style("opacity", 1)
.attr("d", d3.svg.chord().radius(innerRadius));
});
d3.select(self.frameElement).style("height", outerRadius * 5 + "px");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#tooltip {
color: white;
opacity: .9;
background: #333;
padding: 5px;
border: 1px solid lightgrey;
border-radius: 5px;
position: absolute;
z-index: 10;
visibility: hidden;
white-space: nowrap;
pointer-events: none;
}
#circle circle {
fill: none;
pointer-events: all;
}
path.group {
fill-opacity: .8;
}
path.chord {
fill-opacity: .8;
stroke: #000;
stroke-width: .25px;
}
#circle:hover path.fade {
display: none;
}
</style>
</head>
<body>
<div id="tooltip"></div>
<script src="lib/d3.js"></script>
<script src="lib/underscore.js"></script>
<script src="js/mapper.js"></script>
<script>
//*******************************************************************
// CREATE MATRIX AND MAP
//*******************************************************************
d3.csv('data/CNV.csv', function (error, data) {
var mpr = chordMpr(data);
mpr
.addValuesToMap('chr_no')
.addValuesToMap('MUT')
mpr .setFilter(function (row, a, b) {
return (row.chr_no === a.name && row.MUT === b.name) ||
(row.chr_no === b.name && row.MUT === a.name)
})
.setAccessor(function (recs, a, b) {
if (!recs[0]) return 0;
return recs[0].MUT === a.name ? +recs[0].chr_start :
+recs[0].chr_stop ;
});
drawChords(mpr.getMatrix(), mpr.getMap());
});
//*******************************************************************
// DRAW THE CHORD DIAGRAM
//*******************************************************************
function drawChords (matrix, mmap) {
var w = 980, h = 800, r1 = h / 2, r0 = r1 - 110;
var fill = d3.scale.ordinal()
.range(['#c7b570','#c6cdc7','#335c64','#768935',
'#507282','#5c4a56','#aa7455','#574109','#837722',
'#73342d','#0a5564','#9c8f57','#7895a4','#4a5456',
'#b0a690','#0a3542',]);
var chord = d3.layout.chord()
.padding(.04)
.sortSubgroups(d3.descending)
.sortChords(d3.descending);
var arc = d3.svg.arc()
.innerRadius(r0)
.outerRadius(r0 + 20);
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("id", "circle")
.attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");
svg.append("circle")
.attr("r", r0 + 20);
var rdr = chordRdr(matrix, mmap);
chord.matrix(matrix);
var g = svg.selectAll("g.group")
.data(chord.groups())
.enter().append("svg:g")
.attr("class", "group")
.on("mouseover", mouseover)
.on("mouseout", function (d) {
d3.select("#tooltip").style("visibility", "hidden") });
g.append("svg:path")
.style("stroke", "black")
.style("fill", function(d) { return fill(rdr(d).gname); })
.attr("d", arc);
g.append("svg:text")
.each(function(d) { d.angle = (d.startAngle + d.endAngle) / 2;
})
.attr("dy", ".35em")
.style("font-family", "helvetica, arial, sans-serif")
.style("font-size", "9px")
.attr("text-anchor", function(d) { return d.angle > Math.PI ?
"end" : null; })
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + (r0 + 26) + ")"
+ (d.angle > Math.PI ? "rotate(180)" : "");
})
.text(function(d) { return rdr(d).gname; });
var chordPaths = svg.selectAll("path.chord")
.data(chord.chords())
.enter().append("svg:path")
.attr("class", "chord")
.style("stroke", function(d) { return
d3.rgb(fill(rdr(d).sname)).darker(); })
.style("fill", function(d) { return fill(rdr(d).sname); })
.attr("d", d3.svg.chord().radius(r0))
.on("mouseover", function (d) {
d3.select("#tooltip")
.style("visibility", "visible")
.html(chordTip(rdr(d)))
.style("top", function () { return (d3.event.pageY -
170)+"px"})
.style("left", function () { return (d3.event.pageX -
100)+"px";})
})
.on("mouseout", function (d) {
d3.select("#tooltip").style("visibility", "hidden") });
function chordTip (d) {
var p = d3.format(".0%"), q = d3.format("0d")
return "Choromosome information:<br/>"
+ q(d.sname) + " overlap with " + d.tname +" " +
"<br/>chromosome starts at"+" "+ d.sdata +" " +
"<br/>chromosome ends at"+ " "+ d.tdata
}
}
function mouseover(d, i) {
d3.select("#tooltip")
.style("visibility", "visible")
.html(groupTip(rdr(d)))
.style("top", function () { return (d3.event.pageY - 80)+"px"})
.style("left", function () { return (d3.event.pageX - 130)+"px";})
chordPaths.classed("fade", function(p) {
return p.source.index != i
&& p.target.index != i;
});
}
}
</script>

d3.js zoomable map too small in the beginning

I'm trying to modify the example of a zoomable map of the United States, provided by mbostock to fit with Europe.
At the point I've been able to get it sort of, it's so small in the beginning!
I've looked at everything trying to change the presentation size in the beginning, i.e. before the zoom, to be larger, but I've not been able to figure it out. How to achieve this?
All the code is here.
But really, it's just the following short file and an eu.json file:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.background {
fill: none;
pointer-events: all;
}
#states {
fill: #aaa;
}
#states .active {
fill: orange;
}
#state-borders {
fill: none;
stroke: #fff;
stroke-width: 0.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
</style>
<body>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.19/topojson.min.js"></script>
<script>
var width = 960;
var height = 500;
var centered;
var projection = d3.geo.mercator();
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
var g = svg.append("g");
d3.json("eu.json", function(error, data) {
if (error) throw error;
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(data, data.objects.europe).features)
.enter().append("path")
.attr("d", path)
.on("click", clicked);
g.append("path")
.datum(topojson.mesh(data, data.objects.europe, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);
});
function clicked(d) {
var x, y, k;
if (d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;
}
g.selectAll("path")
.classed("active", centered && function(d) { return d === centered; });
g.transition()
.duration(750)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");
}
</script>

Categories

Resources