如何在不更改坐标的情况下转换(旋转)svg 文本元素?

Sta*_*hns 2 javascript svg bar-chart d3.js

我是这个 d3.js 的新手。在这里,我尝试使用 d3.v3.js 库绘制条形图。在这里,我面临着一些问题。我试图在 y 轴上包含度量标签。但是一旦我将标签转换为 -90 度,它的位置就会自动改变。

这是我用来绘制的代码:

    svg.append("g")
    .attr("id","x_axis")
    .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)");
    // .attr("transform", "translate(" + bandSize + ", 0)")

    svg.append("g")
    .attr("class", "x axis")
    .attr("id","dimLabel")
    .append("text")
    .style("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height+55) 
    .text(dimensionLabels[0]);




    svg.append("g")
    .attr("id","y_axis1")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("class", "label")
    //.attr("transform", "rotate(-90)")
    .attr("y", function(d){return y(d3.max(data, function(d) { return d.Metric1; }));});


    //Measure Labels
    svg.append("g")
    .attr("class", "y axis")
    .attr("id","measureLabels")
    .append("text")
    .style("text-anchor", "end")
    .attr("x", 0)
    .attr("y", height/2) 
    .text(measureLabels[0]+", "+measureLabels[1])
    .attr("transform", "rotate(-90)");
Run Code Online (Sandbox Code Playgroud)

输出图像:

在此处输入图片说明

任何帮助是极大的赞赏。

Ger*_*ado 8

您现在看到的是预期的结果,因为属性的rotate功能是transform围绕原点 (0,0) 旋转元素,而不是围绕其中心旋转。

最简单的解决方案是删除您的attr("x")和attr("y")并使用相同的定位文本transform:

var width = 300,
  height = 300;
var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);
var text = svg.append("text")
  .text("Sum (sales), Sum (quantity)")
  .attr("text-anchor", "middle")
  .attr("transform", "translate(20," + (height / 2) + ") rotate(-90)")
Run Code Online (Sandbox Code Playgroud)
svg {
  border: 1px solid gray;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是的中心设定rotate为相同x和y值:

var width = 300,
  height = 300;
var svg = d3.select("body")
  .append("svg")
  .attr("width", width)
  .attr("height", height);
var text = svg.append("text")
  .text("Sum (sales), Sum (quantity)")
  .attr("text-anchor", "middle")
  .attr("x", 20)
  .attr("y", 150)
  .attr("transform", "rotate(-90, 20, 150)")
Run Code Online (Sandbox Code Playgroud)
svg {
  border: 1px solid gray;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v3.min.js"></script>
Run Code Online (Sandbox Code Playgroud)