Home > front end >  Does plotly have a way to convert a date on the x-axis to a day of the week?
Does plotly have a way to convert a date on the x-axis to a day of the week?

Time:10-25

I created a line chart in Plotly from a dataset on crime and it is set up roughly how I need it, but I wanted to convert the x-axis tick labels from the date and time it has currently (see below), to a day of the week. For example on the graph the first point is at 2022/06/25 which was a Saturday. I want the label to say just Sat. My table also contains a column that has the day of the week in it for each date, but I can't figure out how to change that day for the date.

Worst case, I would need to hard code each tick label on the x-axis?

Any input is appreciated. Thank you!

My code:

df = pd.read_csv("test.csv")

        df = df[(df['Occurrence_Category'] == 'Non-Violent')]

        df = df.groupby(['Reported_Date', 'Day_of_Week'], as_index=False).size()

        print(df)

        fig = px.line(
            df,
            x='Reported_Date',
            y='size',
            labels={'size': 'Number of Occurrences', 'Reported_Date': 'Day of the Week'},
            title="Number of Non-Violent Crimes in the last 90 days"

        )
        fig.update_layout(
            xaxis=dict(
                tickmode='linear',
                tick0=1,
                dtick=1
            ),
            yaxis=dict(
                tickmode='linear',
                tick0=0,
                dtick=25
            ),
        )


        fig.show()

Edit: here is the dict of the first 10 rows.

data_dict = 
    {'Reported_Date': {0: '2022/06/25 12:00:00 00', 1: '2022/06/26 12:00:00 00', 2: '2022/06/27 12:00:00 00', 3: '2022/06/28 12:00:00 00', 4: '2022/06/29 12:00:00 00', 5: '2022/06/30 12:00:00 00', 6: '2022/07/01 12:00:00 00', 7: '2022/07/02 12:00:00 00', 8: '2022/07/03 12:00:00 00', 9: '2022/07/04 12:00:00 00'}, 'Day_of_Week': {0: 'Sat', 1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed', 5: 'Thu', 6: 'Fri', 7: 'Sat', 8: 'Sun', 9: 'Mon'}, 'size': {0: 113, 1: 94, 2: 165, 3: 141, 4: 153, 5: 129, 6: 65, 7: 104, 8: 74, 9: 167}}

When I print the df, I get:

The filtered dataframe

My current graph:

enter image description here

CodePudding user response:

All you have to do is to convert the Reported_Date to datetime type such that:

df['Reported_Date'] = df['Reported_Date'].apply(pd.to_datetime)

and specify the tickformat to extract the week day, and remove other parameters to format x-axis as follows:

fig.update_layout(
            xaxis=dict(
                tickformat = '%a'   #<----- this is the format to get weekday
            ),
            yaxis=dict(
                tickmode='linear',
                tick0=0,
                dtick=25
            ),
        )

enter image description here

  • Related