0

In the docs for plotly.py tick formatting here, it states that you can set the tickmode to array and just specify the tickvals and ticktext e.g.

import plotly.graph_objects as go

go.Figure(go.Scatter(
    x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    y = [28.8, 28.5, 37, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9]
))

fig.update_layout(
    xaxis = dict(
        tickmode = 'array',
        tickvals = [1, 3, 5, 7, 9, 11],
        ticktext = ['One', 'Three', 'Five', 'Seven', 'Nine', 'Eleven']
    )
)

fig.show()

But this does not seem to work when tickvals is a list of datetime objects.

What I want to do is show an x-axis tick for each point in my scatter plot where the x values are all datetime objects but this does not seem to work. No error is thrown and the graph is rendered as if I did not try update the x ticks. My code for this is below:

# lambda expression to convert datetime object to string of desired format
date_to_string_lambda = lambda x: x.strftime("%e %b")
fig.update_layout(
    xaxis = dict(
        tickmode = 'array',
        # all points should have a corresponding tick
        tickvals = list(fig.data[0].x),
        # datetime value represented as %e %b string i.e. space padded day and abreviated month. 
        ticktext = list(map(date_to_string_lambda, list(fig.data[0].x))),
    )
)

Instead of showing a tick for each value it goes to the default tick mode and shows ticks at intervals i.e.

Image of graph produced

The values for layout when print(fig) is run after the above code are below, where the xaxis dict is important. Note that the tickvals are no longer of type datetime.

'layout': {'hovermode': 'x',
               'legend': {'title': {'text': ''}, 'tracegroupgap': 0, 'x': 0.01, 'y': 0.98},
               'margin': {'b': 0, 'l': 0, 'r': 0, 't': 0},
               'template': '...',
               'title': {'text': ''},
               'xaxis': {'anchor': 'y',
                         'domain': [0.0, 1.0],
                         'fixedrange': True,
                         'tickmode': 'array',
                         'ticktext': [27 Apr,  3 May,  9 May, 13 May, 20 May],
                         'tickvals': [2020-04-27 00:00:00, 2020-05-03 00:00:00,
                                      2020-05-09 00:00:00, 2020-05-13 00:00:00,
                                      2020-05-20 00:00:00],
                         'title': {'text': 'Date'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'fixedrange': True, 'title': {'text': 'Total Tests'}}}

This seems to be a bug with plotly.py, so is there a workaround for this?

  • [Plotly: How to change the format of the values for the x axis?](https://stackoverflow.com/questions/59828508/plotly-how-to-change-the-format-of-the-values-for-the-x-axis) I find this answer to be very helpful – r-beginners Jun 05 '20 at 14:32

0 Answers0