簡體   English   中英

d3-旋轉x軸標簽

[英]d3 - Rotate x-axis labels

我正在嘗試這張

在此處輸入圖片說明

與我的數據。

我想旋轉x-axis標簽。

這是代碼:

var timeLabels = svg.selectAll(".timeLabel")
          .data(times)
          .enter().append("text")
            .text(function(d) { return d; })
            .attr("x", function(d, i) { return i * gridSize; })
            .attr("y", 0)
            .style("text-anchor", "end")
            .attr("transform", "translate(" + gridSize / 2 + ", -6)rotate(-90)")
            .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });

但是我得到的結果是。 整個標簽在一條直線上旋轉到-90度。 相反,我希望將每個標簽旋轉到-90度。 這樣

在此處輸入圖片說明

我什至嘗試使用.attr("transform", function(d) {return "translate(" + gridSize / 2 + ", -6)rotate(-90)"})但沒有幫助。

結果:

在此處輸入圖片說明

幫助將非常高興。

問題在於,旋轉元素時,它會繞局部坐標系的原點(0,0)旋轉。 如果您要旋轉的元素不在原點附近,則它最終可能會移動很遠的距離,並且可能會完全移到圖表之外。

有兩種解決方法:

  1. 使用“ transform”屬性而不是x和y屬性放置標簽。 這樣,標簽的坐標系-包括(0,0)旋轉點-將與它一起定位,並且旋轉將在您期望的位置進行。 @Manoj提供的代碼遵循該系統,但假定您使用的是默認的xAxis函數。 對於自定義軸標簽代碼,標簽的y值為0,而x值由函數確定。 您只需要將這些值移動到transform屬性中,請注意整體位置的轉換於旋轉和調整:

     var timeLabels = svg.selectAll(".timeLabel") .data(times) .enter().append("text") .text(function(d) { return d; }) .attr("transform", function(d, i) { return "translate(" + ( i * gridSize) + ",0)" + "translate(" + gridSize / 2 + ", -6)rotate(-90)"; } ) .style("text-anchor", "end") .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); }); 

    當然,您可以將這兩個翻譯語句組合在一起,例如:

      .attr("transform", function(d, i) { return "translate(" + ( (i + 0.5) * gridSize) + ",-6)" + "rotate(-90)") 
  2. 或者,您可以通過在旋轉語句中指定旋轉中心,包括要旋轉的點的x和y值:

     var timeLabels = svg.selectAll(".timeLabel") .data(times) .enter().append("text") .text(function(d) { return d; }) .attr("x", function(d, i) { return i * gridSize; }) .attr("y", 0) .attr("transform", function(d, i) { return "translate(" + gridSize / 2 + ", -6)" + "rotate(-90 "+ ((i + 0.5) * gridSize) + " " + (-6) +")"; } ) .style("text-anchor", "end") .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); }); 

    如您所見,此版本具有相當的重復性,因為我們必須兩次計算標簽的位置-一次定位標簽,一次設置旋轉中心。 您會看到為什么大多數示例(以及d3軸功能)使用平移來放置標簽,以便可以將它們旋轉到位。

試試這個代碼:

小提琴

 svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("id", "x")
    .attr("transform", "translate(0," + (h) + ")")
    .call(xAxis)
    .selectAll("text")
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", function (d) {
    return "rotate(-90)";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM