使用tickformat

时间:2017-09-19 13:42:42

标签: javascript d3.js plotly

是否可以使用tickformat将格式添加到xaxis和yaxis刻度?

这个想法是将轴的长名称剪切为:

axiswithaverylongname --> axisw...

在情节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"

1 个答案:

答案 0 :(得分: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>