0
0
Matplotlibdata~5 mins

Ranking charts in Matplotlib

Choose your learning style9 modes available
Introduction

Ranking charts help us see the order of items based on their values. They make it easy to compare and find the top or bottom items.

You want to show the best-selling products in a store.
You need to display the top students by their test scores.
You want to compare countries by their population size.
You want to highlight the most popular movies by box office earnings.
Syntax
Matplotlib
import matplotlib.pyplot as plt

# Data: items and their values
items = ['A', 'B', 'C', 'D']
values = [10, 30, 20, 40]

# Sort data by values descending
sorted_items = [x for _, x in sorted(zip(values, items), reverse=True)]
sorted_values = sorted(values, reverse=True)

# Create bar chart
plt.bar(sorted_items, sorted_values)
plt.title('Ranking Chart')
plt.xlabel('Items')
plt.ylabel('Values')
plt.show()

We sort the data so the highest values appear first.

Bar charts are a simple way to show rankings visually.

Examples
This example shows fruit ranked by quantity.
Matplotlib
items = ['Apple', 'Banana', 'Cherry']
values = [50, 20, 30]

# Sort descending
sorted_items = [x for _, x in sorted(zip(values, items), reverse=True)]
sorted_values = sorted(values, reverse=True)

plt.bar(sorted_items, sorted_values)
plt.show()
This example uses a horizontal bar chart to rank students by scores.
Matplotlib
import matplotlib.pyplot as plt

names = ['John', 'Anna', 'Mike']
scores = [88, 92, 85]

# Sort by scores descending
sorted_names = [n for _, n in sorted(zip(scores, names), reverse=True)]
sorted_scores = sorted(scores, reverse=True)

plt.barh(sorted_names, sorted_scores)
plt.title('Student Scores Ranking')
plt.xlabel('Score')
plt.show()
Sample Program

This program shows a ranking chart of the top 5 countries by population using a vertical bar chart.

Matplotlib
import matplotlib.pyplot as plt

# Sample data: countries and their populations (millions)
countries = ['USA', 'India', 'China', 'Brazil', 'Nigeria']
populations = [331, 1380, 1441, 213, 206]

# Sort countries by population descending
sorted_countries = [c for _, c in sorted(zip(populations, countries), reverse=True)]
sorted_populations = sorted(populations, reverse=True)

# Create ranking bar chart
plt.bar(sorted_countries, sorted_populations, color='skyblue')
plt.title('Top 5 Countries by Population (millions)')
plt.xlabel('Country')
plt.ylabel('Population (millions)')
plt.show()
OutputSuccess
Important Notes

Always sort your data before plotting to show correct rankings.

Use labels and titles to make the chart easy to understand.

Colors can help make the chart more attractive and clear.

Summary

Ranking charts show items ordered by their values.

Sorting data is key to making ranking charts.

Bar charts are a simple and effective way to display rankings.