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

如何按Y轴市值占比降序排列加密货币柱状图?

解决方法

要让柱状图按市值占比降序排列,核心是先对数据框按目标列(市值或市值占比)降序排序,再进行绘图。以下是两种可行的修改方案:

方案一:先筛选真正的市值TOP10(推荐)

原代码直接取前10行可能并非按市值排序后的TOP10,先按市值降序再筛选更符合"前10大加密货币"的定义:

#Declaring these now for later use in the plots
TOP_CAP_TITLE = 'Top 10 market capitalization'
TOP_CAP_YLABEL = '% of total cap'

# 先按市值降序排序,再取前10行
cap_sorted = cap.sort_values('market_cap_usd', ascending=False)
cap10 = cap_sorted.iloc[:10,]

# Calculating market_cap_perc
cap10 = cap10.assign(market_cap_perc = round(cap10['market_cap_usd']/sum(cap['market_cap_usd'])*100,2))

# Plotting the barplot with the title defined above 
fig, ax = plt.subplots(1,1)
ax.bar(cap10['symbol'], cap10['market_cap_perc'])
ax.set_title(TOP_CAP_TITLE)
ax.set_ylabel(TOP_CAP_YLABEL)
plt.show()

方案二:对已有cap10按市值占比排序

如果确认原cap.iloc[:10,]就是需要的10个币种,仅需调整顺序,可在计算完占比后排序:

#Declaring these now for later use in the plots
TOP_CAP_TITLE = 'Top 10 market capitalization'
TOP_CAP_YLABEL = '% of total cap'

# Selecting the first 10 rows and setting the index
cap10 = cap.iloc[:10,]

# Calculating market_cap_perc
cap10 = cap10.assign(market_cap_perc = round(cap10['market_cap_usd']/sum(cap['market_cap_usd'])*100,2))

# 按市值占比降序排序
cap10_sorted = cap10.sort_values('market_cap_perc', ascending=False)

# Plotting the barplot with the title defined above 
fig, ax = plt.subplots(1,1)
ax.bar(cap10_sorted['symbol'], cap10_sorted['market_cap_perc'])
ax.set_title(TOP_CAP_TITLE)
ax.set_ylabel(TOP_CAP_YLABEL)
plt.show()

关键说明

  • sort_values('列名', ascending=False)会将数据框按指定列降序排列,确保X轴的加密货币顺序对应Y轴市值占比从高到低。
  • 方案一逻辑更严谨,能保证筛选出的是真正市值最高的10个币种。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:15:53