import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
# Load the data from the CSV file
data_path = "E:/My Learning Stuff/AI/ML/sales_data.csv"
df = pd.read_csv(data_path)
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y %H:%M')
# Extract year from 'Date'
df['Year'] = df['Date'].dt.year
# Group by Year for Bar Chart
yearly_sales = df.groupby('Year')['Sales_Amount'].sum()
# Group by Region for Pie Chart
region_sales = df.groupby('Region')['Sales_Amount'].sum()
# Create a figure and two subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
# Bar chart for Yearly Sales
bars = ax1.bar(yearly_sales.index, yearly_sales.values, color='b')
ax1.set_title('Yearly Sales Amount')
ax1.set_xlabel('Year')
ax1.set_ylabel('Sales Amount')
# Adding value labels to each bar
for bar in bars:
height = bar.get_height()
ax1.annotate(f'{height:.2f}',
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
# Format x-axis to display years as integers
ax1.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, _: int(x)))
# Pie chart for Sales Distribution by Year
ax2.pie(yearly_sales, labels=[str(year) for year in yearly_sales.index], autopct='%1.1f%%')
ax2.set_title('Sales Distribution by Year')
# Adjust layout
plt.tight_layout()
plt.show()
Leave a comment