【问题标题】:Sorting and Plotting Output of Pandas GroupbyPandas Groupby 的输出排序和绘图
【发布时间】:2017-06-13 17:22:07
【问题描述】:

这里有一个更乏味的问题,但希望有人能提供帮助。我正在尝试绘制一个汇总值(按星期几分组),但显示日期缩写并按星期几编号排序(即显示星期一,首先使用索引 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)

正如您所见,它不像我希望的那样在星期几索引上排序,希望有人有一个聪明的技巧。此外,如果有一种简单的方法可以将 jupyter notebook 单元格输入到堆栈溢出中,这将有助于了解更多问题。

谢谢!

【问题讨论】:

    标签: python matplotlib graph jupyter-notebook


    【解决方案1】:

    如果我理解正确,名为 signup_dayofweek 的图表是正确的,您只是想在 x 轴上有不同的标签?!

    在这种情况下,只需添加

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

    (这里是.set_xticklabels的文档)

    【讨论】:

    • 感谢您的快速回复!可能很明显,但总的来说我对 Python 比较陌生。我现在收到了一个 attr 错误:AttributeError: 'AxesSubplot' object has no attribute 'set_xlabels' 我会继续研究这个虽然不应该太难
    • 对不起,我的意思是 _xtick标签。更正了答案。
    • 你是美丽的人类,现在我的图表几乎和我一样美丽。谢谢!
    • 不要个人化。 ;-) 但如果这回答了您的问题,请考虑 accepting it
    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2020-12-25
    • 2019-02-13
    • 2019-02-02
    • 2019-12-04
    • 2019-08-16
    • 2017-02-07
    相关资源
    最近更新 更多