python - 根据 y 轴中的值对条形图中的条形进行排序

标签 python pandas dataframe matplotlib cryptocurrency

所以我正在 datacamp 中做这个指导项目,它本质上是关于探索一段时间内各种加密货币的市值。尽管我知道获得输出的其他方法,但我坚持使用建议的方法。

所以我需要为排名前 10 的加密货币(x 轴)及其市值份额(y 轴)制作一个条形图。我能够获得所需的输出,但我想更进一步并按降序对栏进行排序。目前,它是根据相应加密货币的首字母排序的。这是代码,

#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))


# 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()

enter image description here

最佳答案

我已经用虚拟数据复制了您的代码,并输出了绘图,这是您正在寻找的排序图吗?只需要使用 df.sort_values() 对数据框进行排序

import pandas as pd
import matplotlib.pyplot as plt

d = {'BCH': 8, 'BTC': 55, 'ETH': 12, 'MIOTA': 4, 'ADA': 0.5, 'BTG': 0.8, 'XMR': 0.7, 'DASH': 1, 'LTC': 0.99, 'XRP': 2.5}
cap = pd.DataFrame({'symbol': d.keys(), 'market_cap_perc': d.values()})

#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 = cap10.sort_values('market_cap_perc', ascending=False)    #add this line

# 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()

enter image description here

关于python - 根据 y 轴中的值对条形图中的条形进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73633436/

相关文章:

python - 为什么我的散点图没有显示颜色?

python - 如何使用 pandas 处理多索引数据

python - pandas 系列中的独特值计数

python - Pandas Apply 函数引用列名

r - 如何遍历R中的数据帧列表

python - 使用自定义 Python 脚本在 Ansible Tower 中自定义凭据

python - 是否有用于查找数字列和分类列的 python 函数?

python - 如何在 matplotlib 中向水平条形图添加标签?

r - 将条件语句添加到 R 中的 'apply' 函数中

r - 在我的数据框中以其他列为条件填充一列,并使用第三列中的值