Ben Saunders
Ben Saunders

Reputation: 1069

Sorting and Plotting Output of Pandas Groupby

Bit of a more tedious question here but hoping someone can help. I'm trying to graph an aggregate value (group by day of week) but display the day abbreviation and order by the day of week number (i.e. display Mon, order it first with index 0).

def Format_plot(plot):
plot.spines["top"].set_visible(False)    
plot.spines["right"].set_visible(False)
plot.yaxis.set_ticks_position("left")
plot.xaxis.set_ticks_position("bottom")   

#For purposes of mapping
days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}  
ds['signup_weekday'] = ds['signup_dayofweek'].apply(lambda x: days[x])
ds = ds.sort_values(by = 'signup_date')
first_ride_rate = {
    'success': lambda x: 1.0*sum(x)/len(x)
    }

def GraphMe(item):
    de = ds[pd.notnull(ds[item])]
    if item == 'signup_weekday':
        sorter = 'signup_dayofweek'
    else:
        sorter = item
    de = de.sort_values(by = sorter)

    total_avg = 1.0*sum(de['success'])/len(de['success'])

    plot = de.groupby(item).agg(first_ride_rate).plot(kind = 'bar',legend=None, title = "Share of signups to complete a first trip")

    Format_plot(plot)
    plot.axhline(y=total_avg, color = 'orange')
    plot.set_xlabel(item)
    plot.set_ylabel('Share of Signups to Complete')
    print sorter

for item in ['signup_dayofweek','signup_weekday']:
    GraphMe(item)

Notebook Snapshot

As you can see it isn't ordering as I'd like to on the day of week index, hoping someone has a clever hack. Also if there's an easy way to input jupyter notebook cells into stack overflow would be helpful to know for further questions.

Thanks!

Upvotes: 1

Views: 707

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339765

If I understand correctly the graph called signup_dayofweek is correct, you just want to have a different labeling on the x-axis?!

In that case simply add

plot.set_xticklabels([days[i] for i in range(7)])

(here would be the documentation of .set_xticklabels)

Upvotes: 1

Related Questions