Home > Software design >  Sorting the bars in the barchart based on the values in y axis
Sorting the bars in the barchart based on the values in y axis

Time:09-07

So I am doing this guided project in datacamp and it is essentially about Exploring the MarketCap of various Cryptocurrencies over the time. Even though I know other means to get the output, I am sticking to the proposed method.

So I need to make a bar graph for the top 10 cryptocurrencies(x axis) and their share of marketcap (y axis). I am able to get the desired output but I want to go one step up and sort the bar in the descending order. Right now, it is sorted based on the first letter of the respective crypto currencies. Here is the code,

#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

CodePudding user response:

I've replicated your code with dummy data, and output the plot, is this the sorted plot you're looking for? Only need to sort the dataframe using 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

CodePudding user response:

You can sort cap10 before plotting:

cap10 = cap10.sort_values(by='market_cap_perc', ascending=False)
fig, ax = plt.subplots(1,1)
...
  • Related