Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

javascript - How to transform (rotate) svg text element without changing coordinates?

I'm new to this d3.js. Here I'm trying to draw a bar chart using the d3.v3.js library. Here I'm facing few problems. I have tried to include measure labels onto the y-axis. But once I transform the labels -90 degree its position is automatically changing.

Here's the code I'm used to drawing:

    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)");

Output Image:

enter image description here

Any help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you see right now is the expected result, because the rotate function of the transform attribute rotates the element around the origin (0,0), not around its center.

The easiest solution is dropping your attr("x") and attr("y") and positioning the text using the same 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)")
svg {
  border: 1px solid gray;
}
<script src="https://d3js.org/d3.v3.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...