2016-04-07 16 views
0

凡例のテキストに値の代わりにパーセンテージを表示しようとしています。 formats.percentageを使ってみましたが、実際にはテキストが表示されません。d3.jsの凡例に占める割合

var legend = svg.selectAll(".legend") 
       .data([0].concat(colorScale.quantiles()), function(d) { return d; }); 

legend.enter().append("g").attr("class", "legend"); 

legend.append("rect") 
    .attr("x", function(d, i) { return legendElementWidth * i; }) 
    .attr("y", height) 
    .attr("width", legendElementWidth) 
    .attr("height", gridSize/2) 
    .style("fill", function(d, i) { return colors[i]; }); 

legend.append("text") 
    .attr("class", "mono") 
    // .text(function(d) { return "≥ " + Math.round(d); }) -- this was original 
    // replaced with below piece 
    .text(function(d) { 
     var r = colors.invertExtent(d); 
     return formats.percent(r[0]); 
    } 
    .attr("x", function(d, i) { return legendElementWidth * i; }) 
    .attr("y", height + gridSize); 

legend.exit().remove(); 

答えて

1

あなたはD3の書式設定ツールを使用することができます。https://github.com/mbostock/d3/wiki/Formatting

それを使用するには、次のようにします。

d3.format(' insert format parameter here ')(insert value here); 

を代わりにformats.percent(R [0])の;

あなたのケースでは、それは次のようになります。

.text(d3.format('%')(r[0])); 

はで述べたように、ちょうど「それは 『%』で100と接尾辞を掛け」、あなたの値の後に「%」を追加ていないことにかかわらず、注意してくださいdoc。以下は

ダミーの番号でそれを使用する方法の例です:

var r = [ 0.4, 80]; //Whatever values you have in r 
 

 
var s = d3.select('body') 
 
    .append('svg') 
 
    .attr('width', 500) 
 
    .attr('height', 500); 
 

 
s.append('text') 
 
    .text(d3.format('%')(r[0])) //Thats where you apply the format : 0.4 -> 40% 
 
    .attr('x', 10) 
 
    .attr('y', 20); 
 

 
s.append('text') 
 
    .text(d3.format('%')(r[1])) 
 
    .attr('x', 10) 
 
    .attr('y', 40);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 

 
<body> 
 
</body>

+0

完璧。私はパーセンテージ形式で出力を得ました。ありがとう – Cini09