可以使用tickformat向x轴和y轴刻度添加格式吗?

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

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"

最佳答案

据我所知,无法直接通过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>

10-06 04:04