所以我在 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()

uj5u.com熱心網友回復:
我已經用虛擬資料復制了您的代碼,并輸出了圖,這是您正在尋找的排序圖嗎?只需要使用排序資料框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()

uj5u.com熱心網友回復:
cap10您可以在繪圖前進行排序:
cap10 = cap10.sort_values(by='market_cap_perc', ascending=False)
fig, ax = plt.subplots(1,1)
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505639.html
標籤:Python 熊猫 数据框 matplotlib 加密货币
