Instagram
youtube
Facebook
Twitter

Add Titles and Labels to a Plot

Description:
This program enhances a bar chart by adding a title and axis labels to clearly represent revenue by product.

Code Explanation:
● Used a bar chart to visualize revenue by product.

● Added plt.title() to display the chart title at the top.

● Used plt.xlabel() to label the X-axis with 'Product Name'.

● Used plt.ylabel() to label the Y-axis with 'Total Revenue'.

● Used tight_layout() to adjust spacing and avoid overlap.

 

Program:

import matplotlib.pyplot as plt
import pandas as pd

# Sample data
data = {
    'OrderID': [101, 102, 103, 104],
    'Product': ['Laptop', 'Tablet', 'Smartphone', 'Headphones'],
    'Quantity': [2, 5, 3, 10],
    'Price': [750, 300, 500, 50],
    'Date': ['2025-01-01', '2025-01-01', '2025-01-02', '2025-01-02']
}

# Create DataFrame
df = pd.DataFrame(data)

# Calculate revenue
df['Revenue'] = df['Quantity'] * df['Price']

# Group by Product
revenue_by_product = df.groupby('Product')['Revenue'].sum()

# Plot with title and labels
plt.figure(figsize=(8, 5))
plt.bar(revenue_by_product.index, revenue_by_product.values, color='teal')
plt.title('Revenue by Product')  # Title
plt.xlabel('Product Name')       # X-axis label
plt.ylabel('Total Revenue')      # Y-axis label
plt.tight_layout()
plt.show()

 

Output: