Convert Result to Percentage in d3
I am just starting to learn d3.js + line chart with legend and tooltips. And I can get it to work, but I want the yAxis result to be in percentage format. Tried using tickFormat, but somehow it didn't convert my raw number to a percentage. T__T
Here is my 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 this part but it 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 appears to be the problem in my previous code? If I am not going to work on the client side, I am considering setting it up on the server side. But too much work.
source to share
d3.format(".0%")
will not scale. All it does is just multiply by 100 and add% to the end. (And I believe that .0% will not add any precision. If you want precision in tenth place, use .1% instead. I don't know if that was necessary)
You might want to use d3.scale.linear () to first scale your data so that it is in the range 0 to 1. And then you can create a yscale that uses domains 0 to 1, which will correspond to 0% -100% on the final y-axis.
//Run data through this pre-scaling.
prescale = d3.scale.linear()
.domain([dataMin, dataMax])
.range([0,1])
//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")
.scale(yScale)
.tickFormat(formatter)
Hope it helps.
source to share