D3分组条形图:如何旋转x轴刻度的文本?

时间:2014-01-06 10:05:42

标签: javascript svg d3.js bar-chart axis-labels

我正在使用分组条形图(http://bl.ocks.org/mbostock/3887051),但x轴的文字非常长,如附图所示。如何旋转文字?谢谢。 enter image description here

3 个答案:

答案 0 :(得分:13)

可以找到合理的解决方案here

结果如下:

enter image description here

确保您完全理解这部分代码:

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")  
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", "rotate(-65)");

-65是标签文字旋转的角度,单位为度。

此外,您应该增加底部的边距,以便不会剪切旋转的文本。

警告:最后浏览器不可避免地呈现旋转文本(D3只是创建由浏览器解释的适当的svg),并且他们执行渲染旋转文本的糟糕工作(与高级绘图或图表软件相反)。

此外,相关的StackOverflow问题:

rotate-x-axis-text-in-d3

how-to-rotate-x-axis-text-in-dimple-js

答案 1 :(得分:2)

使用SVG transform 属性rotate,

此变换定义指定围绕给定点的旋转度数

试试这段代码:

<强> DEMO

 svg.append("g") // Add the X Axis
    .attr("class", "x axis")
    .attr("id", "x")
        .attr("transform", "translate(0," + (h) + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", function (d) {
        return "rotate(-30)";
    });

答案 2 :(得分:0)

您可能要考虑使用D3FC,它可以替代支持该功能的D3轴组件。

D3FC具有一个适配器组件,如果发生碰撞,它们将自动旋转轴标签:

const axis = fc.axisLabelRotate(fc.axisOrdinalBottom(foodScale));

这里正在起作用:

enter image description here

全面披露-我是D3FC库的维护者和贡献者!

相关问题