Instagram
youtube
Facebook
Twitter

Load CSV with Pandas and Visualize with Matplotlib

Description:
A Python program that loads a CSV file using pandas and visualizes product-wise revenue using a bar chart.


Code Explanation:

Imports pandas for data manipulation and matplotlib.pyplot for visualization.
Reads the CSV file "sales_data.csv" using pd.read_csv().
Creates a new column Revenue by multiplying the Quantity and Price.
Groups the data by 'Product' and sums the revenue using groupby() and sum().
Plots a bar chart of total revenue per product using plot(kind='bar').
Adds a title and axis labels with plt.title(), plt.xlabel(), and plt.ylabel().
plt.grid(True) shows grid lines for better readability.
plt.tight_layout() adjusts layout spacing, and plt.show() displays the chart.

sales_data.csv File:

OrderID,Product,Quantity,Price,Date
101,Laptop,2,750,2025-01-01
102,Tablet,5,300,2025-01-01
103,Smartphone,3,500,2025-01-02
104,Headphones,10,50,2025-01-02

 

Program:

import pandas as pd
import matplotlib.pyplot as plt

# Load CSV file
df = pd.read_csv("sales_data.csv")  # Make sure the file is in the correct path

# Calculate revenue per product
df['Revenue'] = df['Quantity'] * df['Price']
revenue_by_product = df.groupby('Product')['Revenue'].sum()

# Plot revenue by product
plt.figure(figsize=(6, 5))
revenue_by_product.plot(kind='bar', color='orange')

# Add labels and title
plt.title("Total Revenue by Product")
plt.xlabel("Product")
plt.ylabel("Revenue")
plt.grid(True)

# Show the plot
plt.tight_layout()
plt.show()

 

Output: