繁体   English   中英

D3.js 旋转垂直条形图标签

[英]D3.js Rotate Vertical Bar Graph Labels

我是 D3.js 的新手,并使用以下来自 D3.js 的示例为我的一个 Web 应用程序创建一个简单的仪表板。

http://bl.ocks.org/NPashaP/96447623ef4d342ee09b

我的要求是将每个条形的最高值标签垂直旋转 90 度。

我通过添加“转换”属性更改了以下方法。 然后标签没有正确对齐。

//Create the frequency labels above the rectangles.
        bars.append("text").text(function(d){ return d3.format(",")(d[1])})
            .attr("x", function(d) { return x(d[0])+x.rangeBand()/2; })
            .attr("y", function(d) { return y(d[1])-5; })
            .attr("text-anchor", "middle")
            .attr("transform", function(d) { return "rotate(-90)" });

我试图找到解决方案很长时间,但找不到。 下面给出了我的代码的链接。

https://jsfiddle.net/vajee555/7udmyj1k/

谁能给我一个想法如何存档?

谢谢!

编辑:我在这里解决了这个问题。

http://jsfiddle.net/vajee555/7udmyj1k/5/

请记住,当您旋转元素时, xy坐标会发生变化:它们不再与图表的坐标相关,而是与元素的新旋转方向相关。 因此,您需要以不同方式计算xy属性。

通过旋转 -90 度,您的 x 轴将翻转为 y,而 y 将翻转为 -x:

在此处输入图片说明

我进行了一些小的像素调整以使其看起来美观,例如我添加到 y 坐标的+8和添加到 x 坐标的+5 ,但微调取决于您。

// Create the frequency labels above the rectangles.
bars.append("text").text(function(d){ return d3.format(",")(d[1])})
    .attr('transform', 'rotate(-90)')
    .attr("y", function(d) { return x(d[0]) + x.rangeBand()/2 + 4; })
    .attr("x", function(d) { return -y(d[1]) + 5; });

此外,更改hG.update()函数中坐标的计算方式:

// transition the frequency labels location and change value.
bars.select("text").transition().duration(500)
    .text(function(d){ return d3.format(",")(d[1])})
    .attr("x", function(d) { return -y(d[1]) + 5; });

请参阅此处的工作小提琴: https : //jsfiddle.net/teddyrised/7udmyj1k/2/

//Create the frequency labels above the rectangles.
    bars.append("text").text(function(d){ return d3.format(",")(d[1])})
        .attr("x", function(d) { return x(d[0])+x.rangeBand()/2; })
        .attr("y", function(d) { return y(d[1])-5; })
        .attr("text-anchor", "middle")
        .attr("transform",  "rotate(-90,0,0)" ); 

如上更改最后一行。

暂无
暂无

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

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