ueke
ueke

Reputation: 33

Formatting text from axis ticks in plotly using tickformat

Is possible to add format to the xaxis and yaxis ticks using tickformat?

The idea is cut long names of axis as:

axiswithaverylongname --> axisw...

In the plotly api reference there's and example to format dates https://plot.ly/javascript/reference/#layout-xaxis-tickformat

and also they refer to the d3 documentation https://github.com/d3/d3-format/blob/master/README.md

from the plotly reference:

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"

Upvotes: 0

Views: 3456

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31709

As far as I know there is no way of doing it directly via tickformat but a few lines of JavaScript code will fix it for you.

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

Using d3's seleectAll wet get all text labels on the x-axis and update the text with the first 5 letters of the initial label.

You can either do it automatically or when the button is pressed in the example below.

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>

Upvotes: 3

Related Questions