简体   繁体   English

不要让matplotlib自动调整x轴的顺序

[英]do not let matplotlib automatically adjust the order of x axis

Here is my little data: 这是我的小数据:

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]})

The order of OfficeName is exactly what I want. OfficeName的顺序正是我想要的。 But, when I try to draw a bar chart: 但是,当我尝试绘制条形图时:

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

The chart looks like this: 该图表如下所示:

在此处输入图片说明

You can see that the order of x axis is automatically changed. 您会看到x轴的顺序已自动更改。 This is really bad for my work. 这真的对我的工作不利。 What I should do to make the chart show the bars just based on the order in my data? 如何使图表仅根据数据中的顺序显示条形图?

Try this code: 试试这个代码:

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()

So Here I made a little edit to your code: 因此,在这里我对您的代码进行了一些编辑:

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')

This gives you the desired output: 这将为您提供所需的输出: 在此处输入图片说明

For more please see the documenationa: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html#pandas.DataFrame.plot.bar 有关更多信息,请参见文档: https ://pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame.plot.bar.html#pandas.DataFrame.plot.bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM