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

如何在Matplotlib中绘制条形图时将Y轴设置为降序排列?

Matplotlib条形图实现Y轴降序排列

要让Matplotlib绘制的条形图按Y轴数值降序排列,核心是先对数据按金额从大到小排序,再绘图,具体步骤如下:

1. 整理并排序数据

先把给出的项目和金额对应好,需要把带$和逗号的金额字符串转换成可计算的数值,再按金额降序排序:

# 原始数据
data = [
    ("Axie Infinity", "$4,074,436,594"),
    ("Crypto Punks", "$2,265,241,216"),
    ("Bored Ape Yacht Club", "$2,221,448,934"),
    ("Mutant Ape Yacht Club", "$1,566,494,617"),
    ("Art Blocks", "$1,265,723,876")
]

# 转换金额为数值并按降序排序
sorted_data = sorted(data, key=lambda x: int(x[1].replace('$', '').replace(',', '')), reverse=True)
names = [item[0] for item in sorted_data]
amounts = [int(item[1].replace('$', '').replace(',', '')) for item in sorted_data]

2. 绘制降序条形图

用Matplotlib绘制条形图,此时X轴是排序后的项目名称,Y轴是对应金额,条形会自动按降序排列:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.bar(names, amounts)

# 优化显示效果
plt.ylabel("交易金额")
plt.title("NFT项目总交易额(降序)")
plt.xticks(rotation=45, ha='right')  # 旋转X轴标签避免重叠

plt.tight_layout()
plt.show()

用Pandas简化操作(可选)

如果用Pandas处理数据会更简洁:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(data, columns=["项目", "交易额"])
# 转换交易额为数值类型
df["交易额"] = df["交易额"].str.replace('$', '').str.replace(',', '').astype(int)
# 按交易额降序排序
df_sorted = df.sort_values(by="交易额", ascending=False)

# 绘图
df_sorted.plot(kind="bar", x="项目", y="交易额", figsize=(10,6), legend=False)
plt.ylabel("交易金额")
plt.title("NFT项目总交易额(降序)")
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.show()

这样绘制出来的条形图就会和你要求的样式一致,从最高的Axie Infinity到最低的Art Blocks依次排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:51:22