关于javascript:使用tickformat从轴刻度中格式化文本

Formatting text from axis ticks in plotly using tickformat

是否可以使用tickformat向x轴和yaxis刻度添加格式?

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

1
axiswithaverylongname --> axisw...

在plotly api参考中有格式化日期的示例
https://plot.ly/javascript/reference/#layout-xaxis-tickformat

,它们也参考了d3文档
https://github.com/d3/d3-format/blob/master/README.md

引自参考文献:

1
2
3
4
5
6
7
8
9
10
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"

据我所知,没有办法直接通过tickformat进行操作,但是几行JavaScript代码将为您解决问题。

1
2
3
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个字母更新文本。

您可以自动执行此操作,也可以在以下示例中按下按钮时执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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) + '...');
    }
  });
});
1
2
3
<script src="https://cdn.plot.ly/plotly-latest.min.js">

<button id="cleanButton">Clean x-axis</button>