简体   繁体   English

d3 y轴标签位置

[英]d3 y axis label position

I have a grouped bar chart design that has each bar amount immediately above the bar instead of the y axis bar on the far left. 我有一个分组的条形图设计,每个条形图的数量紧接在条形上方,而不是最左侧的y轴条形图。

I have added the text like so... 我添加了这样的文字...

svg.selectAll(".text")
.data(data)
.enter()
.append("text")
.attr("class","label")
  .attr("x", function(d) { return x1(d.rate) })
  //.attr("y", function(d) { return y(d.value) + 1; })
.attr("dy", ".75em")
.text(function(d) {return d.value; });

But i cant seem to obtain the x and y values according to the bar position and the actual text of the d.value isn't getting inserted. 但是我似乎无法根据条形图位置获得x和y值,并且未插入d.value的实际文本。

Sample here: https://jsfiddle.net/6p7hmef1/7/ 此处的示例: https : //jsfiddle.net/6p7hmef1/7/

That's because the data bound to the texts that you're adding isn't right. 这是因为绑定到您要添加的文本的数据不正确。

If you add a console.log as follows, you'll be able to see why the labels aren't being inserted. 如果按如下所示添加console.log,您将能够查看为什么未插入标签。 Check for the outputs in console. 在控制台中检查输出。 Console log fiddle 控制台日志小提琴

.text(function(d) {console.log(d); return d.value; });

One approach would be to append the texts to the bar groups ("slice" in your case). 一种方法是将文本附加到栏组(在您的情况下为“切片”)。 Just like you do for the bars. 就像您为酒吧所做的一样。 Here's a fiddle doing this: JS Fiddle Demo 这是一个小提琴: JS Fiddle Demo

    slice.selectAll(".text")
    .data(function(d) { return d.values; })
    .enter()
    .append("text")
    .attr("class","label");
  slice.selectAll('text.label')
    .attr("x", function(d) { return x1(d.rate)+ x1.rangeBand()/3 })
    .attr("y", function(d) { return y(d.value) + 1; }).attr('dy', '-0.4em')
    .text(function(d) {return d.value; });

This might look weird as the texts are shown before the transition of the bars. 这可能看起来很奇怪,因为在过渡栏之前显示了文本。 So changing the value of texts once the bars are shown seems like the right approach to me. 因此,在显示条形之后更改文本的值似乎对我来说是正确的方法。 (dx and dy attributes can be adjusted as per the requirement) (可以根据要求调整dx和dy属性)

Here's the final fiddle : JS FIDDLE 这是最后的小提琴JS FIDDLE

I'm using the "end" callback for every transition and changing the text values accordingly. 我在每次转换时都使用“结束”回调,并相应地更改了文本值。

.each('end', function () {
    d3.select(this.parentNode).selectAll('text.label')
        .attr("x", function(d) { return x1(d.rate)+ x1.rangeBand()/3 })
        .attr("y", function(d) { return y(d.value) + 1; }).attr('dy', '-0.4em')
        .text(function(d) {return d.value; });
})

Hope this helps. 希望这可以帮助。 :) Let me know if any part of the code isn't understandable. :)让我知道代码的任何部分是否无法理解。

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

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