简体   繁体   English

工具提示中的 d3.js 格式编号

[英]d3.js format number in tooltip

I'm building a d3 graph with a tooltip which needs to display the number of units.我正在构建一个带有工具提示的 d3 图表,该工具提示需要显示单位数。 I need to format the numbers so they look like "Units: 225,247" rather than what I'm getting now which is "Units: 225247".我需要格式化数字,使它们看起来像“单位:225,247”,而不是我现在得到的“单位:225247”。

var div = d3.select('body').append('div')
.attr('class', 'tooltip')
.style('opacity', 0);

Then然后

 rect.data(data)
        .enter().append('rect')
        .attr('width', (d, i) => x(d.units))
        .attr('height', y.bandwidth)
        .attr('y', (d, i) => y(d.sizeBand))//connects to data map

        .style('fill', d => colorScale(d.units))

        .on('mouseover', function(d, i, n){
            d3.select(n[i])
            .transition()
            .duration(100)
            .style('opacity', 0.7);

            div.transition()
                .duration(200)
                .style('opacity', 0.9);                      

            div.html('<p> Units: '+ d.units +'</p>' + '<p> Size Band: '+ d.sizeBand + '</p>')                    
                .style('left', (d3.event.pageX - 50) + 'px')
                .style('top', (d3.event.pageY - 100) + 'px')                                       
           })

           .on('mouseout', function(d, i, n){
            d3.select(n[i])
            .transition()
            .duration(50)
            .style('opacity', 1)
            .style('fill', d => colorScale(d.units))//color scale

            div.transition()
                .duration(500)
                .style('opacity', 0)
          })

I know the format code I need is d3.format(',d') but I don't know where to place it or how to use it in a tooltip.我知道我需要的格式代码是d3.format(',d')但我不知道在哪里放置它或如何在工具提示中使用它。

I hope this makes sense (This is my first project in D3 in my first web dev job)我希望这是有道理的(这是我在第一个 web 开发工作中的第一个 D3 项目)

d3.format(',d') sets a function so one way to use it is to define as a variable and then call it later d3.format(',d')设置一个 function 所以使用它的一种方法是定义为一个变量,然后稍后调用它

const formater =  d3.format(',d');
formater(NUMBER TO FORMAT);

on your example, apply to the numbers that make sense, I'm not sure which numbers you want to format, but you will get the idea.在您的示例中,适用于有意义的数字,我不确定您要格式化哪些数字,但您会明白的。

 const formater =  d3.format(',d');
 div.html('<p> Units: '+ formater(d.units) +'</p>' + '<p> Size Band: '+ formater(d.sizeBand) + '</p>')                    
     .style('left', (d3.event.pageX - 50) + 'px')
     .style('top', (d3.event.pageY - 100) + 'px')

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

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