我是 D3.js 的新手,并使用 D3.js 中的以下示例为我的一个 Web 应用程序创建一个简单的仪表板。
http://bl.ocks.org/NPashaP/96447623ef4d342ee09b
我的要求是将每个条形的顶部值标签垂直旋转 90 度。
我通过添加“transform”属性更改了以下方法。那么标签就无法正确对齐。
//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/
有人可以告诉我如何存档吗?
谢谢!
编辑: 我已经解决了这里的问题。
最佳答案
请记住,当您旋转元素时,x
和 y
坐标会发生变化:它们不再相对于图表的坐标,而是相对于图表的坐标。元素的新旋转方向。因此,您需要以不同的方式计算 x
和 y
属性。
通过旋转 -90deg,你的 x 轴将翻转到 y,y 轴将翻转到 -x:
我做了一些小的像素调整,使其看起来美观,例如我添加到 y 坐标的 +8
和我添加的 +5
到 x 坐标,但微调取决于您。
// 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; });
请参阅此处的工作 fiddle :https://jsfiddle.net/teddyrised/7udmyj1k/2/
关于javascript - D3.js 旋转垂直条形图标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30866972/