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

2024-09-28 21:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的小数据:

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

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

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

图表如下所示:

enter image description here

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


Tags: 数据dataframe顺序图表meanlocpd条形图
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()

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

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

这将为您提供所需的输出: enter image description here

有关更多信息,请参阅文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html#pandas.DataFrame.plot.bar

相关问题 更多 >