javascript - Adding value labels to D3 bar chart -


i want add value labels black text above each bar in bar chart. code inspired http://bl.ocks.org/mbostock/3885304. i've posted below data file. i've attempted add code snippet @ end of index.html create value labels, don't text added graph.

index.html

<!doctype html> <meta charset="utf-8"> <style>  .bar {   fill: steelblue;   shape-rendering: crispedges; }  .bar text {   //fill: black;   font: 11x sans-serif;   stroke: black; }  .bar:hover {   fill: brown; }  .axis {   font: 11x sans-serif; }  .axis path, .axis line {   fill: none;   stroke: #000;   shape-rendering: crispedges; }  .x.axis path {   display: none; }  </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script>  var margin = {top: 20, right: 20, bottom: 90, left: 55},     width = 400 - margin.left - margin.right,     height = 500 - margin.top - margin.bottom;  var x = d3.scale.ordinal()     .rangeroundbands([0, width], .1);  var y = d3.scale.linear()     .range([height, 0]);  var xaxis = d3.svg.axis()     .scale(x)     .orient("bottom");  var yaxis = d3.svg.axis()     .scale(y)     .orient("left")     .ticks(10, "%");  var svg = d3.select("body").append("svg")     .attr("width", width + margin.left + margin.right)     .attr("height", height + margin.top + margin.bottom)   .append("g")     .attr("transform", "translate(" + margin.left + "," + margin.top + ")");  d3.tsv("data.tsv", type, function(error, data) {   x.domain(data.map(function(d) { return d.group; }));   //y.domain([0, d3.max(data, function(d) { return d.frequency; })]);   y.domain([0, 1]);    svg.append("g")       .attr("class", "x axis")       .attr("transform", "translate(0," + height + ")")       .call(xaxis)       .selectall("text")           .style("text-anchor", "end")         //.attr("dx", "-.8em")         //.attr("dy", ".15em")         .attr("dx", "-.6em")         .attr("dy", ".35em")         .attr("transform", function(d) {             return "rotate(-45)"              });    svg.append("g")       .attr("class", "y axis")       .call(yaxis)     .append("text")       .attr("transform", "rotate(-90)")       .attr("y", 6)       .attr("dy", ".71em")       .style("text-anchor", "end")       .text("frequency");    var bar = svg.selectall(".bar")       .data(data)     .enter().append("rect")       .attr("class", "bar")       .attr("x", function(d) { return x(d.group); })       .attr("width", x.rangeband())       .attr("y", function(d) { return y(d.frequency); })       .attr("height", function(d) { return height - y(d.frequency); });     // formatter counts.    var formatcount = d3.format(",.0f");      // add value labels    valuelabels = bar.append("text")     .attr("dy", ".75em")     .attr("y", 6)     .attr("x", function(d) { return x(d.group); })     .attr("text-anchor", "middle")     .text(function(d) { return formatcount(y(d.frequency)); });  });  function type(d) {   d.frequency = +d.frequency;   return d; }  </script> 

data.tsv

group   frequency 1-9 weeks   .036197 10-12 weeks .0457085 13 weeks    .0714285 14 weeks    .846666 

based on reference @lars kotthoff , material @ https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/math/ceil, coded following:

<!doctype html> <meta charset="utf-8"> <style>  .bar {   fill: steelblue;   shape-rendering: crispedges; }   .bar text {   //fill: black;   font: 8x sans-serif;   stroke: black; }  .datalabel {   font-size: 10px;   fill: white; }  .bar:hover {   fill: brown; }  .axis {   font: 11x sans-serif; }  .axis path, .axis line {   fill: none;   stroke: #000;   shape-rendering: crispedges; }  .x.axis path {   display: none; }  </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script>  var margin = {top: 20, right: 20, bottom: 90, left: 55},     width = 400 - margin.left - margin.right,     height = 500 - margin.top - margin.bottom;  var x = d3.scale.ordinal()     .rangeroundbands([0, width], .1);  var y = d3.scale.linear()     .range([height, 0]);  var xaxis = d3.svg.axis()     .scale(x)     .orient("bottom");  var yaxis = d3.svg.axis()     .scale(y)     .orient("left")     .ticks(10, "%");  var svg = d3.select("body").append("svg")     .attr("width", width + margin.left + margin.right)     .attr("height", height + margin.top + margin.bottom)   .append("g")     .attr("transform", "translate(" + margin.left + "," + margin.top + ")");  d3.tsv("interactions.tsv", type, function(error, data) {   x.domain(data.map(function(d) { return d.group; }));   //y.domain([0, d3.max(data, function(d) { return d.frequency; })]);   y.domain([0, 1]);    svg.append("g")       .attr("class", "x axis")       .attr("transform", "translate(0," + height + ")")       .call(xaxis)       .selectall("text")           .style("text-anchor", "end")         //.attr("dx", "-.8em")         //.attr("dy", ".15em")         .attr("dx", "-.6em")         .attr("dy", ".35em")         .attr("transform", function(d) {             return "rotate(-45)"              });    svg.append("g")       .attr("class", "y axis")       .call(yaxis)     .append("text")       .attr("transform", "rotate(-90)")       .attr("y", 6)       .attr("dy", ".71em")       .style("text-anchor", "end")       .text("frequency");      var bar = svg.selectall(".bar")       .data(data)       .enter().append("g");      bar.append("rect")       .attr("class", "bar")       .attr("x", function(d) { return x(d.group); })       .attr("width", x.rangeband())       .attr("y", function(d) { return y(d.frequency); })       .attr("height", function(d) { return height - y(d.frequency); });      bar.append("text")     .attr("class", "datalabel")     .attr("x", function(d) { return x(d.group) + x.rangeband()/2; })     .attr("y",  function(d) { return y(0) - 10; } )     .attr("dy", ".35em")     .attr("text-anchor", "middle")     .text(function(d) { return math.ceil10(d.frequency*100, -1) + "%"; });     // formatter counts.    var formatcount = d3.format(",.0f");  });  function type(d) {   d.frequency = +d.frequency;   return d; }  (function () {     /**      * decimal adjustment of number.      *      * @param {string}  type  type of adjustment.      * @param {number}  value number.      * @param {integer} exp   exponent (the 10 logarithm of adjustment base).      * @returns {number} adjusted value.      */     function decimaladjust(type, value, exp) {         // if exp undefined or zero...         if (typeof exp === 'undefined' || +exp === 0) {             return math[type](value);         }         value = +value;         exp = +exp;         // if value not number or exp not integer...         if (isnan(value) || !(typeof exp === 'number' && exp % 1 === 0)) {             return nan;         }         // shift         value = value.tostring().split('e');         value = math[type]( + (value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));         // shift         value = value.tostring().split('e');         return  + (value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));     }      // decimal round     if (!math.round10) {         math.round10 = function (value, exp) {             return decimaladjust('round', value, exp);         };     }     // decimal floor     if (!math.floor10) {         math.floor10 = function (value, exp) {             return decimaladjust('floor', value, exp);         };     }     // decimal ceil     if (!math.ceil10) {         math.ceil10 = function (value, exp) {             return decimaladjust('ceil', value, exp);         };     } })();  </script> 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -