Instagram
youtube
Facebook
Twitter

Plot Only Top 5 Products by Revenue

Description:
This code filters the top 5 products based on revenue and plots them as a bar chart using matplotlib.
​​​​​​
Code Explanation:

🔹 Data Preparation:

  • A sample dataset with products and their revenue is created using a dictionary.

  • Converted to a pandas.DataFrame.

🔹 Filtering:

  • The DataFrame is sorted by 'Revenue' in descending order.

  • .head(5) selects the top 5 products.

🔹 Plotting:

  • A bar chart is created for the top 5 products.

  • plt.bar() takes product names and their corresponding revenue.

  • Bar color set to 'skyblue'.

🔹 Formatting:

  • Title and axis labels added.

  • plt.grid(axis='y') enables grid lines on the y-axis for readability.

  • plt.tight_layout() ensures labels don’t overlap.

🔹 Displaying the Plot:

  • plt.show() displays the final chart.

Program:
 

import pandas as pd
import matplotlib.pyplot as plt

# Sample product revenue data
data = {
    'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
    'Revenue': [1200, 2500, 1800, 2200, 2700, 1600, 2100]
}
df = pd.DataFrame(data)

# Sort the data by revenue and select top 5 products
top5_df = df.sort_values(by='Revenue', ascending=False).head(5)

# Plotting the top 5 products by revenue
plt.figure(figsize=(8, 5))
plt.bar(top5_df['Product'], top5_df['Revenue'], color='skyblue')

# Formatting
plt.title('Top 5 Products by Revenue')
plt.xlabel('Product')
plt.ylabel('Revenue')
plt.grid(axis='y')
plt.tight_layout()

# Show the plot
plt.show()


Output: