javascript - D3 chart for visualizing data by sector and overall and algo explained -


i need create d3 chart in following link: d3 bubble chart (data displayed overall , sector)

below screenshots of charts:

overall view: enter image description here

sector view: enter image description here

i have searched lot, not able find codebase or example same. so, i'm not sure of how can achieve same.

please share code/pointers achieve same chart using d3.

thanks in advance, manish kumar

below can find code chart in link. in source code of website. suggest learn it, wouldn't copy it...

(function() {  var margin = {top: 20, right: 95, bottom: 10, left: 125},     width = 970 - margin.left - margin.right,     height,     tickextension = 20; // extend grid lines beyond scale range  var formatpercent = d3.format(".0%"),     formattenthpercent = d3.format(".1%"),     formatnumber = d3.format(",.3s"),     formatdollars = function(d) { return (d < 0 ? "-" : "") + "$" + formatnumber(math.abs(d)).replace(/g$/, "b"); };  var nameall = "s.\x26p.\xa0500 companies";  var x = d3.scale.linear()     .domain([0, .6])     .rangeround([0, width - 60])     .clamp(true)     .nice();  var y = d3.scale.ordinal();  var y0 = d3.scale.ordinal()     .domain([nameall])     .range([150]);  var r = d3.scale.sqrt()     .domain([0, 1e9])     .range([0, 1]);  var z = d3.scale.threshold()     .domain([.1, .2, .3, .4, .5])     .range(["#b35806", "#f1a340", "#fee0b6", "#d8daeb", "#998ec3", "#542788"].reverse());  var xaxis = d3.svg.axis()     .scale(x)     .orient("top")     .ticks(5)     .tickformat(formatpercent);  var yaxis = d3.svg.axis()     .scale(y)     .orient("left")     .ticksize(-width + 60 - tickextension * 2, 0)     .tickpadding(6);  var quadtree = d3.geom.quadtree()     .x(function(d) { return d.x; })     .y(function(d) { return d.y; });  var svg = d3.select(".g-graphic").append("svg")     .attr("height", 420 + margin.top + margin.bottom)     .attr("width", width + margin.left + margin.right)   .append("g")     .attr("transform", "translate(" + margin.left + "," + margin.top + ")");  d3.select(".g-graphic").append("svg")     .style("margin-top", "20px")     .attr("height", 80)     .attr("width", width + margin.left + margin.right)   .append("g")     .attr("transform", "translate(" + margin.left + "," + margin.top + ")")     .call(renderchartkey);  var gx = svg.append("g")     .attr("class", "g-x g-axis")     .call(xaxis);  var ticklast = gx.selectall(".g-x .tick:last-of-type");  ticklast.select("text")     .text(function() { return "\u2265 " + this.textcontent; });  ticklast.select(function() { return this.parentnode.appendchild(this.clonenode(true)); })     .attr("transform", "translate(" + width + ",0)")   .select("text")     .text("n.a.");  var titlex = gx.append("text")     .attr("class", "g-title")     .attr("y", -9)     .style("text-anchor", "end");  titlex.append("tspan")     .attr("x", -20)     .style("font-weight", "bold")     .text("effective tax rate");  titlex.append("tspan")     .attr("x", -20)     .attr("dy", "1em")     .text("2007-12");  d3.tsv("http://graphics8.nytimes.com/newsgraphics/2013/05/13/corporate-taxes/ee84b0191a75f5c652087293ab0efd4710e21f94/companies.tsv", type, function(error, companies) {   var sectors = d3.nest()       .key(function(d) { return d.sector; })       .entries(companies);    // compute overall rate data.   var overallrate = rate(d3.sum(companies, taxes), d3.sum(companies, earnings));    // compute overall rate sector.   sectors.foreach(function(d) {     d.rate = rate(d3.sum(d.values, taxes), d3.sum(d.values, earnings));   });    // sort sectors ascending overall rate.   sectors.sort(function(a, b) {     return a.rate - b.rate;   });    // compute rate each company.   companies.foreach(function(d) {     d.rate = rate(d.taxes, d.earnings);   });    height = 120 * sectors.length;    y       .domain(sectors.map(function(d) { return d.key; }))       .rangepoints([10, height], 1);    svg.append("g")       .attr("class", "g-y g-axis g-y-axis-sector")       .attr("transform", "translate(-" + tickextension + ",0)")       .call(yaxis.scale(y))       .call(yaxiswrap)       .style("stroke-opacity", 0)       .style("fill-opacity", 0)     .selectall(".tick text,.tick tspan")       .attr("x", -95)       .style("text-anchor", "start");    svg.append("g")       .attr("class", "g-y g-axis g-y-axis-overall")       .attr("transform", "translate(-" + tickextension + ",0)")       .call(yaxis.scale(y0))       .call(yaxiswrap);    var companyclip = svg.append("defs").selectall("clippath")       .data(companies)     .enter().append("clippath")       .attr("id", function(d, i) { return "g-clip-company-" + i; })     .append("circle")       .attr("cx", function(d) { return d.cx; })       .attr("cy", function(d) { return d.cy - y0(nameall); })       .attr("r", function(d) { return r(d.capitalization) + 20; });    var gvoronoi = svg.append("g")       .attr("class", "g-voronoi")    gvoronoi.selectall("path")       .data(companies)     .enter().append("path")       .attr("clip-path", function(d, i) { return "url(#g-clip-company-" + + ")"; })       .on("mouseover", mouseover)       .on("mouseout", mouseout);    gvoronoi.call(updatevoronoi,       function(d) { return d.cx; },       function(d) { return d.cy + y0(nameall); },       420);    var sector = svg.append("g")       .attr("class", "g-sector")     .selectall("g")       .data(sectors)     .enter().append("g")       .attr("transform", function(d) { return "translate(0," + y(d.key) + ")"; });    var sectornote = d3.select(".g-sector-notes")       .style("opacity", 0)       .style("display", "none")     .selectall("div")       .data(sectors)     .enter().append("div")       .attr("class", "g-sector-note")       .style("top", function(d) { return y(d.key) + "px"; })       .html(function(d) { return sectornotebyname[d.key]; });    var sectorcompany = sector.append("g")       .attr("class", "g-sector-company")     .selectall("circle")       .data(function(d) { return d.values; })     .enter().append("circle")       .attr("cx", function(d) { return d.cx; })       .attr("cy", function(d) { return d.cy - y(d.sector) + y0(nameall); })       .attr("r", function(d) { return r(d.capitalization); })       .style("fill", function(d) { return isnan(d.rate) ? null : z(d.rate); })       .on("mouseover", mouseover)       .on("mouseout", mouseout);    var sectoroverall = sector.append("g")       .attr("class", "g-overall")       .attr("transform", function(d) { return "translate(" + x(d.rate) + "," + (y0(nameall) - y(d.key)) + ")"; })       .style("stroke-opacity", 0)       .style("fill-opacity", 0);    sectoroverall.append("line")       .attr("y1", -100)       .attr("y2", +127);    var sectoroveralltext = sectoroverall.append("text")       .attr("y", -106);    sectoroveralltext.append("tspan")       .attr("x", 0)       .text(function(d) { return formatpercent(d.rate); });    sectoroveralltext.filter(function(d, i) { return !i; }).append("tspan")       .attr("x", 0)       .attr("dy", "-11")       .style("font-size", "8px")       .text("overall");    var overall = svg.append("g")       .attr("class", "g-overall g-overall-all")       .attr("transform", "translate(" + x(overallrate) + "," + y0(nameall) + ")");    overall.append("line")       .attr("y1", -100)       .attr("y2", +127);    var overalltext = overall.append("text")       .attr("y", -106)       .style("font-weight", "bold");    overalltext.append("tspan")       .attr("x", 0)       .style("font-size", "13px")       .text(formattenthpercent(overallrate));    overalltext.append("tspan")       .attr("x", 0)       .attr("dy", "-14")       .style("font-size", "8px")       .text("overall");    var currentview = "overall";    d3.selectall(".g-content button[data-view]")       .datum(function(d) { return this.getattribute("data-view"); })       .on("click", transitionview);    var searchinput = d3.select(".g-search input")       .on("keyup", keyuped);    var searchclear = d3.select(".g-search .g-search-clear")       .on("click", function() {         searchinput.property("value", "").node().blur();         search();       });    var tip = d3.select(".g-tip");    var tipmetric = tip.selectall(".g-tip-metric")       .datum(function() { return this.getattribute("data-name"); });    d3.selectall(".g-annotations b,.g-sector-notes b")       .datum(function() { return new regexp("\\b" + d3.requote(this.textcontent), "i"); })       .on("mouseover", mouseoverannotation)       .on("mouseout", mouseout);    function keyuped() {     if (d3.event.keycode === 27) {       this.value = "";       this.blur();     }     search(this.value.trim());   }    function search(value) {     if (value) {       var re = new regexp("\\b" + d3.requote(value), "i");       svg.classed("g-searching", true);       sectorcompany.classed("g-match", function(d) { return re.test(d.name) || re.test(d.sector) || (d.symbol && re.test(d.symbol)) || (d.alias && re.test(d.alias)); });       var matches = d3.selectall(".g-match");       if (matches[0].length === 1) mouseover(matches.datum());       else mouseout();       searchclear.style("display", null);     } else {       mouseout();       svg.classed("g-searching", false);       sectorcompany.classed("g-match", false);       searchclear.style("display", "none");     }   }    function transitionview(view) {     if (currentview === view) view = view === "overall" ? "sector" : "overall";     d3.selectall(".g-buttons button[data-view]").classed("g-active", function(v) { return v === view; })     switch (currentview = view) {       case "overall": return void transitionoverall();       case "sector": return void transitionsector();     }   }    function transitionoverall() {     gvoronoi.style("display", "none");      var transition = d3.transition()         .duration(750);      transition.select("svg")         .delay(720)         .attr("height", 420 + margin.top + margin.bottom)         .each("end", function() {           gvoronoi.call(updatevoronoi,             function(d) { return d.cx; },             function(d) { return d.cy + y0(nameall); },             420);         });      transition.select(".g-annotations-overall")         .each("start", function() { this.style.display = "block"; })         .style("opacity", 1);      transition.select(".g-sector-notes")         .style("opacity", 0)         .each("end", function() { this.style.display = "none"; });      transition.selectall(".g-y-axis-sector")         .style("stroke-opacity", 0)         .style("fill-opacity", 0);      transition.selectall(".g-y-axis-overall")         .style("stroke-opacity", 1)         .style("fill-opacity", 1);      var transitionoverall = transition.select(".g-overall-all")         .delay(x(overallrate))         .style("stroke-opacity", 1)         .style("fill-opacity", 1);      transitionoverall.select("line")         .attr("y2", +127);      transitionoverall.select("text")         .attr("y", -106);      var transitionsectoroverall = transition.selectall(".g-sector .g-overall")         .delay(function(d) { return x(d.rate); })         .attr("transform", function(d) { return "translate(" + x(d.rate) + "," + (y0(nameall) - y(d.key)) + ")"; })         .style("stroke-opacity", 0)         .style("fill-opacity", 0);      transitionsectoroverall.select("line")         .attr("y1", -100)         .attr("y2", +127);      transitionsectoroverall.select("text")         .attr("y", -106);      transition.selectall(".g-sector-company circle")         .delay(function(d) { return d.cx; })         .attr("cx", function(d) { return d.cx; })         .attr("cy", function(d) { return d.cy - y(d.sector) + y0(nameall); });   }    function transitionsector() {     gvoronoi.style("display", "none");      var transition = d3.transition()         .duration(750);      transition.select("svg")         .attr("height", height + margin.top + margin.bottom)       .transition()         .delay(720)         .each("end", function() {           gvoronoi.call(updatevoronoi,             function(d) { return d.x; },             function(d) { return y(d.sector) + d.y; },             height);         });      transition.select(".g-annotations-overall")         .style("opacity", 0)         .each("end", function() { this.style.display = "none"; });      transition.select(".g-sector-notes")         .delay(250)         .each("start", function() { this.style.display = "block"; })         .style("opacity", 1);      transition.selectall(".g-y-axis-sector,.g-sector-note")         .delay(250)         .style("stroke-opacity", 1)         .style("fill-opacity", 1);      transition.selectall(".g-y-axis-overall")         .style("stroke-opacity", 0)         .style("fill-opacity", 0);      var transitionoverall = transition.select(".g-overall-all")         .delay(x(overallrate))         .style("stroke-opacity", 0)         .style("fill-opacity", 0);      transitionoverall.select("line")         .attr("y2", height - y0(nameall));      var transitionsectoroverall = transition.selectall(".g-sector .g-overall")         .delay(function(d) { return x(d.rate); })         .attr("transform", function(d) { return "translate(" + x(d.rate) + ",0)"; })         .style("stroke-opacity", 1)         .style("fill-opacity", 1);      transitionsectoroverall.select("line")         .attr("y1", -25)         .attr("y2", +25);      transitionsectoroverall.select("text")         .attr("y", -31);      transition.selectall(".g-sector-company circle")         .delay(function(d) { return d.x; })         .attr("cx", function(d) { return d.x; })         .attr("cy", function(d) { return d.y; });   }    function updatevoronoi(gvoronoi, x, y, height) {     companyclip         .attr("cx", x)         .attr("cy", y);      gvoronoi         .style("display", null)       .selectall("path")         .data(d3.geom.voronoi().x(x).y(y)(companies))         .attr("d", function(d) { return "m" + d.join("l") + "z"; })         .datum(function(d) { return d.point; });   }    function mouseoverannotation(re) {     var matches = sectorcompany.filter(function(d) { return re.test(d.name) || re.test(d.alias); }).classed("g-active", true);     if (d3.sum(matches, function(d) { return d.length; }) === 1) mouseover(matches.datum());     else tip.style("display", "none");   }    function mouseover(d) {     sectorcompany.filter(function(c) { return c === d; }).classed("g-active", true);      var dx, dy;     if (currentview === "overall") dx = d.cx, dy = d.cy + y0(nameall);     else dx = d.x, dy = d.y + y(d.sector);     dy -= 19, dx += 50; // margin fudge factors      tip.style("display", null)         .style("top", (dy - r(d.capitalization)) + "px")         .style("left", dx + "px");      tip.select(".g-tip-title")         .text(d.alias || d.name);      tipmetric.select(".g-tip-metric-value").text(function(name) {       switch (name) {         case "rate": return isnan(d.rate) ? "n.a." : formatpercent(d.rate);         case "taxes": return formatdollars(d.taxes);         case "earnings": return formatdollars(d.earnings);       }     });   }    function mouseout() {     tip.style("display", "none");     sectorcompany.filter(".g-active").classed("g-active", false);   } });  function renderchartkey(g) {   var formatpercent = d3.format(".0%"),       formatnumber = d3.format(".0f");    // position encoding key only.   var x = d3.scale.linear()       .domain([0, .6])       .range([0, 240]);    var xaxis = d3.svg.axis()       .scale(x)       .orient("bottom")       .ticksize(13)       .tickvalues(z.domain())       .tickformat(function(d) { return d === .5 ? formatpercent(d) : formatnumber(100 * d); });    g.append("text")       .attr("x", -25)       .style("text-anchor", "end")       .style("font", "bold 9px sans-serif")       .text("chart key");    var gcolor = g.append("g")       .attr("class", "g-key-color")       .attr("transform", "translate(140,-7)");    gcolor.selectall("rect")       .data(z.range().map(function(d, i) {         return {           x0: ? x(z.domain()[i - 1]) : x.range()[0],           x1: < 4 ? x(z.domain()[i]) : x.range()[1],           z: d         };       }))     .enter().append("rect")       .attr("height", 8)       .attr("x", function(d) { return d.x0; })       .attr("width", function(d) { return d.x1 - d.x0; })       .style("fill", function(d) { return d.z; });    gcolor.call(xaxis);    var gcolortext = g.append("text")       .attr("x", 140 - 6)       .style("text-anchor", "end");    gcolortext.append("tspan")       .style("font-weight", "bold")       .text("color");    gcolortext.append("tspan")       .style("fill", "#777")       .text(" shows effective rate");    var gsize = g.append("g")       .attr("class", "g-key-size")       .attr("transform", "translate(580,-7)");    var gsizeinstance = gsize.selectall("g")       .data([1e9, 10e9, 50e9, 100e9])     .enter().append("g")       .attr("class", "g-sector");    gsizeinstance.append("circle")       .attr("r", r);    gsizeinstance.append("text")       .attr("x", function(d) { return r(d) + 4; })       .attr("dy", ".35em")       .text(function(d) { return "$" + math.round(d / 1e9) + "b"; });    var gsizex = 0;    gsizeinstance.attr("transform", function() {     var t = "translate(" + gsizex + ",3)";     gsizex += this.getbbox().width + 15;     return t;   });    var gsizetext = g.append("text")       .attr("x", 580 - 10)       .style("text-anchor", "end");    gsizetext.append("tspan")       .style("font-weight", "bold")       .text("size");    gsizetext.append("tspan")       .style("fill", "#777")       .text(" shows market capitalization"); }  function yaxiswrap(g) {   g.selectall(".tick text")     .filter(function(d) { return /[ ]/.test(d) && this.getcomputedtextlength() > margin.left - tickextension - 10; })       .attr("dy", null)       .each(function(d) {         d3.select(this).text(null).selectall("tspan")             .data(d.split(" "))           .enter().append("tspan")             .attr("x", this.getattribute("x"))             .attr("dy", function(d, i) { return (i * 1.35 - .35) + "em"; })             .text(function(d) { return d; });       }); }  function taxes(d) {   return d.taxes; }  function earnings(d) {   return d.earnings; }  function rate(taxes, earnings) {   return earnings <= 0 ? nan : taxes / earnings; }  function type(d) {   d.x = +d.x;   d.y = +d.y;   d.cx = +d.cx;   d.cy = +d.cy;   d.taxes *= 1e6;   d.earnings *= 1e6;   d.capitalization *= 1e6;   return d; }  var sectornotebyname = {   "utilities": "utilities benefited 2009 stimulus bill, included tax breaks companies make capital-intensive investments, power plants.",   "information technology": "technology companies can move operations overseas accounting purposes. , younger firms tend have recent losses, holding down sector&rsquo;s overall rate.",   "industrials": "as corporate sector, large industrial companies &mdash; <b>boeing</b>, <b>caterpillar</b>, <b>general electric</b> , <b>honeywell</b> &mdash; pay lower taxes on average small companies.",   "telecom": "<b>verizon</b> had lower effective tax rate rival <b>at&t</b>, despite having similar profits on six-year period.",   "health care": "within health care, managed care companies pay relatively higher tax rates, , makers of equipment, supplies , technology pay relatively lower rates.",   "pharma": "tax breaks research , ability locate operations in low-tax countries have helped pharmaceutical , biotech companies pay low taxes.",   "consumer products": "movie studios , packaged-food company pay more 30 percent, on average. soft-drink companies pay 19 percent, , restaurant companies, 25 percent.",   "materials": "the materials industry (chemicals, minerals, etc.) exemplifies point made tax experts: within industries, tax rates vary greatly, in ways evade simple explanation.",   "financials": "as financial firms have recovered crisis, have paid relatively high tax rates.",   "retailers": "brick-and-mortar retailers, <b>bed bath & beyond</b> , <b>home depot</b>, tend pay high tax rates. online retailers, <b>amazon</b>, face low rates.",   "energy": "large oil companies typically pay high rates, economists argue high rates not cover pollution costs imposed on society.",   "insurance": "many insurers pay lower-than-average rates. <b>a.i.g.</b> &mdash; had $83 billion loss while paying $8 billion in taxes &mdash; drives sector&rsquo;s average up." };  })() 

Comments