You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Seaborn柱状图按Y轴(Amount)降序排列?

How to Sort Seaborn Barplot by Amount (Descending Order)

Absolutely! You can adjust your plot to show bars ordered by the Amount column (largest to smallest) in two straightforward ways:

Option 1: Sort the DataFrame First

First, sort your DataFrame in descending order based on the Amount column, then pass this sorted DataFrame to Seaborn's barplot. This ensures the bars appear in the order of your sorted data:

import seaborn as sns
import matplotlib.pyplot as plt

# Sort the DataFrame by Amount in descending order
df_sorted = df.sort_values('Amount', ascending=False)

# Create the barplot using the sorted data
plot = sns.barplot(x='ID', y='Amount', data=df_sorted)

# Optional: Rotate x-axis labels to prevent overlap (since IDs are long numbers)
plt.xticks(rotation=45)
plt.show()

Option 2: Use the order Parameter (Without Modifying Original DataFrame)

If you don't want to alter your original DataFrame, you can directly specify the order of the ID values using the order parameter. This parameter accepts a list of values defining the sequence of x-axis categories:

import seaborn as sns
import matplotlib.pyplot as plt

# Get the order of IDs sorted by Amount (descending)
id_order = df.sort_values('Amount', ascending=False)['ID'].tolist()

# Create the barplot with the custom order
plot = sns.barplot(x='ID', y='Amount', data=df, order=id_order)

# Optional: Rotate x-axis labels for readability
plt.xticks(rotation=45)
plt.show()

Why This Works

By default, Seaborn's barplot orders x-axis values either by their natural sort order (for numerical values like your ID column) or by the order they appear in the data (for categorical values). By sorting the DataFrame or explicitly setting the order parameter, you override this default behavior to prioritize the Amount values instead.

Both methods will result in the bar with the largest Amount appearing on the far left, and the smallest on the far right—exactly what you're looking for!

内容的提问来源于stack exchange,提问作者Main

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:57:03