javascript - Convert result to percentage in d3 -
i'm starting learn d3.js + line chart legend & tooltips. , i'm able make work want have yaxis result in percentage format. tried using tickformat somehow doesn't convert raw number percentage. t__t
here js code
chart = d3linewithlegend() .xaxis.label('date') .width(700) .height(300) .yaxis.label('frequency'); var svg = d3.select('#histogram svg').datum(data); svg.transition().duration(1000) .attr('width', 700) .attr('height', 300) .call(chart); chart.dispatch.on('showtooltip', function(e) { var offset = $('#histogram').offset(), // { left: 0, top: 0 } left = e.pos[0] + offset.left, top = e.pos[1] + offset.top, // formatter = d3.format(".04f"); formatter = d3.format(".0%"); var yaxis = d3.svg.axis().orient("left").tickformat(formatter);//added part didn't work console.log(yaxis); 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>'; nvtooltip.show([left, top], content); }); chart.dispatch.on('hidetooltip', function(e) { nvtooltip.cleanup(); });
what seem problem in above code? if don't make work on client side i'm thinking of adjusting in server side. work.
d3.format(".0%")
won't scaling. multiply 100 , add % end of it. (and believe .0% add no precision. if want precision tenth's place, use .1% instead. don't know if wanted)
you might want use d3.scale.linear() in order scale data first in range of 0 1. , can create yscale uses domains 0 1, correspond 0% 100% in final y-axis.
//run data through pre-scaling. prescale = d3.scale.linear() .domain([datamin, datamax]) .range([0,1]) //use y-scale in place of potential y-scaling function. yscale = d3.scale.linear() .domain([0, 1]) .range([canvasheightlow, canvasheighthigh]); //afterwards, can use yscale build yaxis formatter = d3.format(".0%"); yaxis = d3.svg.axis().orient("left") .scale(yscale) .tickformat(formatter)
hope helps.
Comments
Post a Comment