[英]How to rotate all text by x degree on x-axis in Javascript
I copied the below snippet form D3 ( https://www.d3-graph-gallery.com/graph/arc_highlight.html ) to create an arc-diagram我复制了以下代码段形式 D3 ( https://www.d3-graph-gallery.com/graph/arc_highlight.html ) 以创建弧形图
var margin = { top: 20, right: 30, bottom: 20, left: 30},
width = 1100 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body of the page
var svg = d3.select("#my_dataviz")
.append("svg").attr("width", width + margin.left + margin.right).attr("height", height + margin.top + margin.bottom)
.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data = { "nodes": [{ "id": 1, "name": "uto-ujamaki"}, {"id": 2, "name": "saske-uchiha"}.......], "links": [{"source": 1, "target": 2}, {"source": 1, "target": 5 }......]};
// List of node names
var allNodes = data.nodes.map(function(d){ return d.name })
// A linear scale to position the nodes on the X axis
var x = d3.scalePoint().range([0, width]).domain(allNodes)
// Add the circle for the nodes
var nodes = svg.selectAll("mynodes").data(data.nodes).enter().append("circle")
.attr("cx", function(d){ return(x(d.name))})
.attr("cy", height-30).attr("r", 8)
.style("fill", "#69b3a2")
// And give them a label
var labels = svg.selectAll("mylabels").data(data.nodes).enter().append("text")
.attr("x", function(d){ return(x(d.name))})
.attr("y", height-10)
.text(function(d){ return(d.name)})
.style("text-anchor", "middle")
// <------ below attribute, it work but rotate whole x-axis instead of node text ---->
// .attr("transform", "translate(250, 0) rotate(60)")
Now the x-axis has labels that are placed horizontally and it overlaps when there is a large number of data/nodes.现在 x 轴有水平放置的标签,当有大量数据/节点时它会重叠。
I thought to rotate the text on the axis by some degree (say 60) to avoid overlapping but when I add the transform attribute it rotates the whole axis instead of node text by 60 degrees.我想将轴上的文本旋转一定程度(比如 60 度)以避免重叠,但是当我添加变换属性时,它会将整个轴而不是节点文本旋转 60 度。 I am a newbie to styling.我是造型的新手。
Solution template解决方案模板
I wished I would have found below link before posting this question, anyways thanks to community.我希望我能在发布这个问题之前找到下面的链接,无论如何感谢社区。 https://www.d3-graph-gallery.com/graph/arc_template.html https://www.d3-graph-gallery.com/graph/arc_template.html
In your code translate function x and y values are hard coded that is why it is causing the issue在您的代码中翻译function x 和 y 值是硬编码的,这就是导致问题的原因
Edit:1编辑:1
var labels = svg
.selectAll("mylabels")
.data(data.nodes)
.enter()
.append("text")
.attr("x", function(d){ return(0)})
.attr("y", 0)
.text(function(d){ return(d.name)})
.attr("transform", function(d){ console.log(d); return( "translate(" + (x(d.name)) + ", " + (height-15) + ") rotate(-45)")})
.style("text-anchor", "middle")
Above changes will work以上更改将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.