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

标签 javascript html d3.js

我是 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/

有人可以告诉我如何存档吗?

谢谢!

编辑: 我已经解决了这里的问题。

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

最佳答案

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

通过旋转 -90deg,你的 x 轴将翻转到 y,y 轴将翻转到 -x:

enter image description here

我做了一些小的像素调整,使其看起来美观,例如我添加到 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/

相关文章:

javascript - 动态创建和删除 HTML 元素

javascript - 在 Vuejs 中使图片可点击

javascript - 不理解 d3.timeParse 的结果?

javascript - '点对点路径'd3可视化性能问题

javascript - D3 V4多系列折线图: Adding data points to lines with same color as lines

Javascript 设置下拉列表的 bool 值

javascript - 使用文本框进行交叉过滤

javascript - 将关联数组从nodejs传递到客户端最终会变成空

html - 左浮动 div 的中心容器

混合了文字和数组的 Javascript 数组