How to sort bars in a bar plot in ascending order (Matplotlib)?

To sort bars in a bar plot in ascending order, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.

  • Make a list of data for bar plots.

  • Create a bar plot using bar() method, with sorted data.

  • To display the figure, use show() method.

Example

Here's how to create a bar plot with bars sorted in ascending order ?

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [3, 5, 9, 15, 12]

plt.bar(range(len(data)), sorted(data), color='red', alpha=0.5)
plt.xlabel('Bar Index')
plt.ylabel('Values')
plt.title('Bar Plot with Ascending Order')

plt.show()

Sorting with Labels

When you have labels for your bars, you need to sort both data and labels together ?

import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D', 'E']
values = [3, 5, 9, 15, 12]

# Sort both lists based on values
sorted_data = sorted(zip(values, categories))
sorted_values, sorted_categories = zip(*sorted_data)

plt.figure(figsize=(8, 4))
plt.bar(sorted_categories, sorted_values, color='blue', alpha=0.7)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Sorted by Values (Ascending)')

plt.show()

Using Pandas for Complex Sorting

For more complex data, pandas provides an easier way to sort ?

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    'category': ['Product A', 'Product B', 'Product C', 'Product D'],
    'sales': [150, 200, 100, 175]
})

# Sort by sales in ascending order
df_sorted = df.sort_values('sales')

plt.figure(figsize=(8, 4))
plt.bar(df_sorted['category'], df_sorted['sales'], color='green', alpha=0.6)
plt.xlabel('Products')
plt.ylabel('Sales')
plt.title('Sales Data Sorted in Ascending Order')
plt.xticks(rotation=45)

plt.show()

Comparison

Method Best For Complexity
sorted() Simple numeric data Low
zip() + sorted() Data with labels Medium
pandas.sort_values() Complex datasets Low (with pandas)

Conclusion

Use sorted() for simple numeric data or pandas sort_values() for datasets with labels. Always sort both values and labels together to maintain data integrity.

Updated on: 2026-03-26T00:22:30+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements