Convert result to percentage in d3

I'm only starting to learn d3.js + Line chart with Legend & Tooltips. And I'm able to make it work but what I want is to have the yAxis result to be in percentage format. Tried using tickFormat but somehow it doesn't convert my raw number to percentage. T__T

Here is my js code

chart = d3LineWithLegend()

var svg ='#histogram svg').datum(data);

  .attr('width', 700)
  .attr('height', 300)

chart.dispatch.on('showTooltip', function(e) {
    var offset = $('#histogram').offset(), // { left: 0, top: 0 }
    left = e.pos[0] + offset.left,
    top = e.pos[1] +,
    // formatter = d3.format(".04f");
    formatter = d3.format(".0%");
    var yAxis = d3.svg.axis().orient("left").tickFormat(formatter);//added this part but it didn't work

    var dateObj = (new Date(e.point[0]));

    var year = dateObj.getFullYear();
    var month = dateObj.getMonth() + 1;
    var day = dateObj.getDate();
    var hours = dateObj.getHours();
    var date = month + '-' + day + '-' + year;
    if(filter === 'hour') {
      date = date + ', ' + hours + ':00';

    var content = '<h3>' + date + '</h3>' +
              '<p>' +
              '<span class="value">' + (e.point[1]) + '</span>' +
              '</p>';[left, top], content);

chart.dispatch.on('hideTooltip', function(e) {

What seem to be the problem in my above code? If I don't make it work on the client side I'm thinking of adjusting this in server side. But too much work.



d3.format(".0%") won't do scaling. All it does is simply multiply by 100 and add a % to the end of it. (And I believe that .0% will add no precision. If you want precision to the tenth's place, use .1% instead. Don't know if this was wanted)

You might want to use d3.scale.linear() in order to scale your data first so that it is in the range of 0 to 1. And then you can create a yscale that uses domains from 0 to 1, which will correspond to 0% to 100% in the final y-axis.

//Run data through this pre-scaling.
prescale = d3.scale.linear()
                   .domain([dataMin, dataMax])

//Use this y-scale in place of another potential y-scaling function.

yScale = d3.scale.linear()
                 .domain([0, 1])
                 .range([canvasHeightLow, canvasHeightHigh]);

//Afterwards, you can use this yScale to build your yAxis

formatter = d3.format(".0%");

yAxis = d3.svg.axis().orient("left")

Hope this helps.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.