【问题标题】:do not let matplotlib automatically adjust the order of x axis不要让matplotlib自动调整x轴的顺序
【发布时间】:2018-12-31 15:22:53
【问题描述】:

这是我的小数据:

aa3=pd.DataFrame({'OfficeName':['Narre Warren','Cannington','Chadstone','1_Mean',
                            'Traralgon','Bondi Junction','Hobart','2_Mean'],
              'Ratio':[0.1,0.2,0.4,0.1,0.43,0.4,0.15,0.32]})

OfficeName 的顺序正是我想要的。但是,当我尝试绘制条形图时:

plt.bar(aa3.loc[:,'OfficeName'],aa3.loc[:,'Ratio'])

图表如下所示:

可以看到x轴的顺序是自动改变的。这对我的工作真的很不利。我应该怎么做才能使图表仅根据数据中的顺序显示条形?

【问题讨论】:

    标签: python pandas matplotlib indexing axis


    【解决方案1】:

    所以我在这里对你的代码做了一点修改:

    import matplotlib.pyplot as plt
    aa3=pd.DataFrame({'OfficeName':['Narre Warren','Cannington','Chadstone','1_Mean',
                                'Traralgon','Bondi Junction','Hobart','2_Mean'],
                  'Ratio':[0.1,0.2,0.4,0.1,0.43,0.4,0.15,0.32]})
    aa3.plot.bar(x="OfficeName",y='Ratio')
    

    这将为您提供所需的输出:

    更多信息请看文档a:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html#pandas.DataFrame.plot.bar

    【讨论】:

    • 谢谢。它有很大帮助。
    • 你能添加一些你自己的解释吗?链接可能会过时。
    • 好的,感谢您指出这一点,我认为我对此没有太多解释,但将来我会记住这一点,然后再点击问题中的帖子。
    【解决方案2】:

    试试这个代码:

    a3=pd.DataFrame({'OfficeName':['Narre Warren', 'Cannington', 'Chadstone', '1_Mean',
                                'Traralgon', 'Bondi Junction', 'Hobart', '2_Mean'],
                  'Ratio':[0.1, 0.2, 0.4, 0.1, 0.43, 0.4, 0.15, 0.32]})
    
    fig, ax = plt.subplots()
    ind = np.arange(a3.loc[:, 'OfficeName'].nunique()) #Creates an array for indices on x-axis 
    
    width = 0.35 #Width of the bar plots
    p1 = ax.bar(ind, a3.loc[:, 'Ratio'], width) #Creates the bar plot for plotting
    
    plt.xticks(ind) #Sets ticks(positions) for the labels to appear. Default starts from -1(we want it to start from 0)
    ax.set_xticklabels(a3.loc[:, 'OfficeName'], ha = 'center') #Write the x labels for each value
    
    ax.set_xlabel('x Group')
    ax.set_ylabel('Ratio')
    plt.show()
    

    【讨论】:

    • 您能否添加一些散文来尽可能详细地解释您所做的事情?
    • @MadPhysicist 当然,添加了 cmets。如果您需要我为特定内容添加评论,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2019-07-25
    • 2022-01-20
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多