Search code examples
javascriptplotlyplotly.js

Display Years as Text vs Numeric Values on Plotly Legend


When displaying a chart with an axis that represents Years, Plotly sees them as numeric values. If there are only a few of them, the legend for the x axis below displays as 2022, 2022.5, 2023, and 2023.5.

var traceA = {
    x: [2022,2023],
    y: [14610178,2598912],
    type: 'bar',
    marker: { color: '932BD4' }
};

The only solution I've found is to add non-numerals, such as x: ['(2022)','(2023)'] but it would be preferable to display just the numerals.

What am I missing in preventing them from being seen as numeric values?


Solution

  • You can make the years in x to be treated as date by setting the x axis type accordingly, though you would have Jul 2022 instead of 2022.5, etc. so you would still need to specify dtick to prevent showing intermediate values, for example :

    const data = [{
      x: [2022, 2023],
      y: [14610178, 2598912],
      type: 'bar',
      marker: { color: '932BD4' }
    }];
    
    const layout = {
      xaxis: {
        type: 'date',
        dtick: 'M12'
      }
    }
    
    Plotly.newPlot('myDiv', data, layout);
    

    You could also just set dtick=1 without changing the axis type. Or, you could set the axis type to 'category', in which case no need to set dtick.