d3.js数字格式未正确显示在工具栏上

d3.js数字格式未正确显示在工具栏上,d3.js,number-formatting,D3.js,Number Formatting,我正在处理一个水平条形图,并希望以特定格式显示每个条形图上的值。我试着用很多方法编写代码,但都没有达到我想要的结果。我正在使用以下代码: data = d3.json('data.json') .then(data => {data .forEach(d => { d.country = d.country; d.population = +d.population * 1000; }); console.log(data); render(data); }); c

我正在处理一个水平条形图,并希望以特定格式显示每个条形图上的值。我试着用很多方法编写代码,但都没有达到我想要的结果。我正在使用以下代码:

data = d3.json('data.json')
.then(data => {data
.forEach(d => {
    d.country = d.country;
  d.population = +d.population * 1000;
});

console.log(data);
render(data);

});

const xValuesNumberFormat = number => d3.format(',.0f')(number);

const xValues = d => d.population;

svg.selectAll('text')
.data(data)
.enter()
.append('text')
.attr('class', 'bar-value')
.attr('x', xPos)
.attr('y', yPos)
.text(xValues)
.attr('transform',`translate(5,`+yScale.bandwidth()/1.5+`)`)
        ;



[
{"country":"China","population":1415046},
{"country":"India","population":1354052},
{"country":"United States","population":326767},
{"country":"Indonesia","population":266795},
{"country":"Brazil","population":210868},
{"country":"Pakistan","population":200814},
{"country":"Nigeria","population":195875},
{"country":"Bangladesh","population":166368},
{"country":"Russia","population":143965},
{"country":"Mexico","population":130759}
]


svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('class', 'rect')
//.attr('x', xPos)
.attr('y', yPos)
.attr('width', xPos)
.attr('height', yScale.bandwidth())

.on('mouseover', function (d)
 {tooltip.style('display', null);})

.on('mouseout', function (d)
{tooltip.style('display', 'none');})

.on('mousemove', function (d)
{
var xPos = d3.mouse(this)[0] ;
var yPos = d3.mouse(this)[1] - 20;
tooltip.attr("transform", "translate("+xPos + "," + yPos +")");
tooltip.select('text').text(d3.format(',.0f')(d.population));
})
;
当我尝试格式化它时,我得到了Nan、undefined和各种其他错误

正如您从图像中看到的,我希望条形图旁边的数字格式与条形图上的数字相同。基本上,我只需要逗号分隔符。谢谢你的帮助。

我知道了

svg.selectAll('text')
.data(data)
.enter()
.append('text')
.attr('class', 'bar-value')
.attr('x', xPos)
.attr('y', yPos)
.text(d => d3.format(',.0f')(+d.population))
.attr('transform', `translate(5,`+yScale.bandwidth()/1.5+`)`);

感谢您抽出时间来投稿。

您的数字是否在数据中以文本形式表示?一些原始数据示例会很有帮助,只要一些示例代码失败。我已经添加了数据和一些额外的代码。我能够正确设置鼠标悬停数值的格式。它的价值观旁边的酒吧,我似乎不能格式相同。谢谢您的时间。如果您传递给
text
函数的数据是格式化的填充值,那么错误就在该值的上游。这表明格式化函数不是获取数字,而是获取字符串、对象、
未定义、
、“NaN”等。请重新检查该函数作为参数接收的内容。你发布的代码有点乱,不完整,所以我不能肯定。