【问题标题】:How to rotate all text by x degree on x-axis in Javascript如何在Javascript中将所有文本在x轴上旋转x度
【发布时间】:2020-12-13 07:26:02
【问题描述】:

我复制了下面的 sn-p 表单 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)") 

现在 x 轴有水平放置的标签,当有大量数据/节点时,它会重叠。

我想将轴上的文本旋转一定程度(比如 60 度)以避免重叠,但是当我添加变换属性时,它会将整个轴而不是节点文本旋转 60 度。我是造型新手。

解决方案模板

我希望我能在发布这个问题之前找到下面的链接,无论如何感谢社区。 https://www.d3-graph-gallery.com/graph/arc_template.html

【问题讨论】:

    标签: javascript css d3.js


    【解决方案1】:

    在您的代码中 translate 函数 x 和 y 值是硬编码的,这就是导致问题的原因

    编辑: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")
    

    以上更改将起作用

    【讨论】:

    猜你喜欢
    • 2013-07-21
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    相关资源
    最近更新 更多