Reputation: 171
Does anyone have any idea why I cannot generate percentage in the following codeIshere (lines 97-117)?
var format=d3.format(".1%");
var percent = format(function(d){
if (d[values[0]]>d[values[1]]) {return (d[values[0]]-d[values[1]])/d[values[0]];}
else {return (d[values[1]]-d[values[0]])/d[values[1]];}});
bar1.append("text")
.attr("class", "label")
.attr("x", function(d) { return x(d.id) + 16; })
.attr("y", function(d) {
if (d[values[0]] > d[values[1]]) {return y(d[values[0]]) - 35;}
else {return y(d[values[1]]) - 35;}})
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("fill", function(d) {
if (d[values[0]] > d[values[1]]) {return "green";}
else {return "red";}})
.text(function(d){
if (d[values[0]]>d[values[1]]) {return "-" + percent;}
else {return percent;}});
I have been playing with it the whole morning and I'm out of ideas. I couldn't find the answer in the other posts.
Any help will be appreciated! Thanks!
Upvotes: 1
Views: 101
Reputation: 1885
One solution is to compute the percentage in the .text(function(d){}) function. (This code may probably be made a bit shorter.)
.text(function(d){
var percent;
if (d[values[0]]>d[values[1]])
{
percent = (d[values[0]]-d[values[1]])/d[values[0]];
}
else
{
percent = (d[values[1]]-d[values[0]])/d[values[1]];
}
if (d[values[0]]>d[values[1]]) {return "-" + percent;}
else {return percent;}});
;
Upvotes: 1
Reputation: 40647
Here is the working code: https://jsfiddle.net/3860zcc3/15/
According to the formatting documentation
https://github.com/mbostock/d3/wiki/Formatting
"In addition to numbers, D3 also supports formatting and parsing dates, and comma-separated values."
If you replace
var percent = format(function(d){
if (d[values[0]]>d[values[1]]) {return (d[values[0]]-d[values[1]])/d[values[0]];}
else {return (d[values[1]]-d[values[0]])/d[values[1]];}}
with a number like
var percent = format(2);
formatting works.
But even a simple function like:
var percent = format(function(d){return 2;});
is not working.
My guess is a function is not supported. So I took your code inside another function and returned that result inside the fiddle.
Upvotes: 2