pandas 为什么seaborn条形图不保留groupby索引的顺序?[副本]

3qpi33ja  于 2023-05-21  发布在  其他
关注(0)|答案(2)|浏览(74)

此问题已在此处有答案

Ordering a barplot by ascending or descending(2个答案)
Sns barplot does not sort sliced values(1个答案)
Issue sorting (in decrescent order) bar plot the top 30 values of my dataframe(1个答案)
Seaborn Bar Plot Ordering(6个答案)
2天前关闭。
我正在尝试创建groupby对象的seaborn条形图。下面是一个例子:

data = {'ID':[1, 2, 3, 1, 2, 3], 
        'value':[10, 20, 30, 100, 200, 300], 
        'other': ['a', 'b', 'c', 'd', 'e','f']
       }
data = pd.DataFrame(data)

我想使用groupby()将数据按ID分组,计算平均值value,并按value降序排序:

grouped = data.groupby('ID').mean()
grouped = grouped.sort_values(by='value', ascending=False)
grouped

现在我想用seaborn的条形图来绘制这个图:

sns.barplot(x=grouped.index, y=grouped['value'])

这就是结果:

该图保留了原始顺序,忽略了我重新分配grouped以更改顺序的事实。
为什么会发生这种情况?我尝试了很多不同的方法,但总是得到相同的结果。

z31licg0

z31licg01#

您始终可以强制执行以下命令:

sns.barplot(x=grouped.index, y=grouped['value'], order=grouped.index)

chy5wohz

chy5wohz2#

也可以将ID转换为字符串:

sns.barplot(x=grouped.index.astype(str), y=grouped['value'])

输出:

相关问题