Skip to content
Advertisement

Change X Axis Values to Days of Week (Mon – Sun) in Seaborn/Pandas

I’m currently doing a sales analysis I found online, and was wondering how I could display the x axis values (Days of the Week) from their current order to Mon – Sun.

I have grouped the days of the week the item was bought using:

    df12 = df.groupby('Weekday Bought').count().sort_values(['Paid'], ascending = False)['Paid']
    display(df12)

Which returns:

    Weekday Bought
    Thursday     65
    Saturday     63
    Monday       58
    Friday       56
    Tuesday      55
    Wednesday    47
    Sunday       44
    Name: Paid, dtype: int64

I want this displayed in descending order, and a graph being displayed with Weekday Bought on the x axis and counted Paid values on the y axis. I have my MatplotLib/Seaborn code to create a line graph as:

    plt.figure(figsize=(15,6))
    chart12 = sns.lineplot(x = 'Weekday Bought', y = 'Paid', 
    data = df12.reset_index(), color = "green")
    plt.xlabel('Weekday Bought', size = 12)
    plt.ylabel('Number Bought', size = 12)
    chart12.set_title('Most Popular Day of Week for Buying', 
    size = 12)
    chart12.set_xticklabels(chart12.get_xticklabels(), 
    rotation=20)
    plt.show()

Which correctly generates a line graph with the correct data on it. I want to adjust this code to display Mon – Sun in order on the x axis. Does anyone know if I could make a list with the days of the week in order, then “plug it in” to my code? Hopefully someone can help me! Thanks!

Note – The Weekday Bought dtype is object

Advertisement

Answer

IIUC, After groupby use reset_index, and do the custom sorting –

df = df.reset_index()
df.Weekday = pd.Categorical(df.Weekday,
                            categories=['Monday', 'Tuesday', 'Wednesday',
                                        'Thursday', 'Friday', 'Saturday', 'Sunday'],
                            ordered=True)

df = df.sort_values('Weekday')

OUTPUT:

     Weekday  Bought
2     Monday      58
4    Tuesday      55
5  Wednesday      47
0   Thursday      65
3     Friday      56
1   Saturday      63
6     Sunday      44
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement