简体   繁体   English

d3.js格式轴统一以百万计

[英]d3.js format axis uniformly in millions

I found this thread and it got me halfway to where I need to be and I'm wondering if anyone knows how I can adjust the solution to fit my needs. 我找到了这个线程 ,它使我半途而废,我想知道是否有人知道如何调整解决方案以满足我的需求。

So if I have some values in the thousands, and some values in the millions, does anyone know how I can set all of the ticks to be formatted in the millions? 因此,如果我有成千上万个值,有几百万个值,有人知道我如何将所有刻度设置成百万个吗? For instance, if I have a value for 800k it would show up as 0.8million instead. 例如,如果我有一个80万的值,它将显示为80万。

This is what I get when using the above solution without adjusting it. 这是使用上述解决方案而不进行调整时得到的。 在此处输入图片说明

You don't need to use a SI prefix in this case. 在这种情况下,您不需要使用SI前缀。 Given this domain: 鉴于此域:

var scale = d3.scaleLinear().domain([200000,1800000])

Going from 200 thousand to 1.8 million, you can simply divide the tick value by 1,000,000 and add a "million" string. 从20万增加到180万,您可以将滴答值除以1,000,000,然后添加一个“百万”字符串。

Here is the demo: 这是演示:

 var svg = d3.select("body") .append("svg") .attr("width", 600) .attr("height", 100); var scale = d3.scaleLinear().domain([200000,1800000]).range([20,550]); var axis = d3.axisBottom(scale).tickFormat(function(d){return d/1000000 + " Million"}); var gX = svg.append("g").attr("transform", "translate(20, 50)").call(axis); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

EDIT : According to the comments, you want to show "million" only in the last tick. 编辑 :根据评论,您只想在最后一刻显示“百万”。 Thus, we have to check if the tick is the last one and conditionally formatting it: 因此,我们必须检查刻度线是否为最后一个,并有条件地对其进行格式化:

var axis = d3.axisBottom(scale).tickFormat(function(d){
    if(this.parentNode.nextSibling){
        return d/1000000;
    } else { 
        return d/1000000 + " Million";
    }
});

Here is the demo: 这是演示:

 var svg = d3.select("body") .append("svg") .attr("width", 600) .attr("height", 100); var scale = d3.scaleLinear().domain([200000,1800000]).range([20,550]); var axis = d3.axisBottom(scale).tickFormat(function(d){ if(this.parentNode.nextSibling){ return d/1000000} else { return d/1000000 + " Million"}}); var gX = svg.append("g").attr("transform", "translate(20, 50)").call(axis); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM