Plotly string versus date

Viewed 39

I am having an issue with a Plotly scatter graph. The X axis is a date in the format YYYY-WW. WW stands for week number. If I convert that to date time format, Plotly is unable to interpret it, since it is expecting a month. If I leave it as a string, then Plotly complains "ValueError: Could not convert value of 'x' ('x') into a numeric type. If 'x' contains stringified dates, please convert to a datetime column.".

I just want Plotly to use X axis as a category for the scatter graph. Not a date, and don't try to convert into numeric type.

year_week = [ '2020-00', '2020-01', '2020-02', '2020-03' ]
num_accidents = [ 2, 3, 4, 5 ]

fig_ = px.scatter(
                     x=year_week,
                     y=num_accidents,
                     trendline='ols',
                     title="Number of Accidents Per Week")

    fig.update_xaxes(type='category')
    fig.update_layout(xaxis_type='category')
    fig.update_traces(mode='lines')
1 Answers

You can convert the date format to datetime using strptime(), which will change it to the right datetime format. Note that %W is for the week-of-year number and it needs to be accompanied by %w, which is the day of the week. The week should start from 01, not 00 as there is not week-0 as far as datetime is concerned. I have made that change. Note that I have added -1 as this will take the first day of the week. The code is shown below. Once created, the date times should show up correctly. I have done an update_xaxes() to demonstrate how to change the axis format, in case you don't like the default as well.

year_week = [ '2020-01', '2020-02', '2020-03', '2020-04' ]
num_accidents = [ 2, 3, 4, 5 ]

import datetime
year_week = [datetime.datetime.strptime(date + '-1',"%Y-%W-%w") for date in year_week]

fig = px.scatter(
                     x=year_week,
                     y=num_accidents,
                     trendline='ols',
                     title="Number of Accidents Per Week")

#fig.update_xaxes(type='category')
#fig.update_layout(xaxis_type='category')
fig.update_traces(mode='lines')
fig.update_xaxes(tickformat="%d-%b-%Y")

enter image description here

Related