2017-09-19 359 views
0

可以使用tickformat將格式添加到xaxis和yaxis ticks中嗎?使用tickformat格式化座標軸上的文本

的想法是切軸長名稱爲:

axiswithaverylongname --> axisw... 

在plotly API參考有和例如格式化日期 https://plot.ly/javascript/reference/#layout-xaxis-tickformat

而且它們指的是D3的文件 https://github.com/d3/d3-format/blob/master/README.md

來自標準參考:

tickformat (string) 
default: "" 
Sets the tick label formatting rule using d3 formatting mini-languages 
which are very similar to those in Python. For numbers, see: 
https://github.com/d3/d3-format/blob/master/README.md#locale_format 
And for dates see: https://github.com/d3/d3-time- 
format/blob/master/README.md#locale_format We add one item to d3's 
date formatter: "%{n}f" for fractional seconds with n digits. For 
example, "2016-10-13 09:15:23.456" with tickformat "%H~%M~%S.%2f" 
would display "09~15~23.46" 

回答

0

據我所知,沒有辦法直接通過tickformat來做,但幾行JavaScript代碼將爲您解決它。

Plotly.d3.selectAll(".xtick text").each(function(d, i) { 
    Plotly.d3.select(this).html(Plotly.d3.select(this).html().substr(0, 5)); 
}); 

使用D3的seleectAll溼獲得在x軸的所有text標籤和與初始標籤的前5個字母更新文本。

您可以自動或在下面的示例中按下按鈕時執行此操作。

var trace1 = { 
 
    x: ["A", "B1", "axiswithaverylongname", "Wow, wait a second, that's way tooooo long"], 
 
    y: [1, 2, 3, 4], 
 
    type: "bar" 
 
}; 
 

 
var myPlot = document.getElementById('myPlot') 
 
Plotly.newPlot('myPlot', [trace1]); 
 
document.getElementById("cleanButton").addEventListener("click", function(){ 
 
    Plotly.d3.selectAll(".xtick text").each(function(d, i) { 
 
    if (Plotly.d3.select(this).html().length > 8) { 
 
     Plotly.d3.select(this).html(Plotly.d3.select(this).html().substr(0, 5) + '...'); 
 
    } 
 
    }); 
 
});
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 
 
<div id="myPlot" style="width:100%;height:100%"></div> 
 
<button id="cleanButton">Clean x-axis</button>

+0

的偉大工程!,是超級乾淨! – ueke