![](/img/trans.png)
[英]How to overlay text on an SVG path element in React without using the coordinates of the path element?
[英]How to transform (rotate) svg text element without changing coordinates?
我是这个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)");
输出图像:
任何帮助是极大的赞赏。
您现在看到的是预期的结果,因为transform
属性的rotate
函数使元素绕原点(0,0)旋转,而不是围绕其中心旋转。
最简单的解决方案是删除attr("x")
和attr("y")
并使用相同的transform
attr("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("transform", "translate(20," + (height / 2) + ") rotate(-90)")
svg { border: 1px solid gray; }
<script src="https://d3js.org/d3.v3.min.js"></script>
另一种解决方案是将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)")
svg { border: 1px solid gray; }
<script src="https://d3js.org/d3.v3.min.js"></script>
我认为您正在寻找CSS属性transform-origin
https://www.w3schools.com/cssref/css3_pr_transform-origin.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.