问题是,当使用GroupBy函数对数据进行分组后,柱状图的顺序会根据分组后的顺序进行绘制,而不是根据原始数据的顺序。为了解决这个问题,我们可以使用Categorical类型来明确指定每个类别的顺序。
下面是一个例子:
import pandas as pd import matplotlib.pyplot as plt from pandas.api.types import CategoricalDtype
df = pd.DataFrame({'fruit': ['apple', 'banana', 'pear', 'apple', 'banana', 'pear'], 'sales': [20, 25, 15, 18, 28, 20]})
grouped = df.groupby(['fruit'])['sales'].sum().reset_index().sort_values('sales', ascending=False)
cat_type = CategoricalDtype(categories=grouped['fruit'], ordered=True)
df['fruit'] = df['fruit'].astype(cat_type)
plt.bar(x='fruit', height='sales', data=df) plt.show()
在这个例子中,首先使用GroupBy函数按水果类别分组,然后按销售量排序。然后我们创建了一个Categorical类型,指定每个类别的顺序,并使用astype函数将'fruit'列转换为Categorical类型。最后,我们使用plt.bar函数绘制柱状图。
使用这种方法,我们可以确保柱状图上的类别顺序与GroupBy函数中指定的顺序相同。