Predictive Sales Analytics and Data Visualization
Predictive Analytics on Product Sales Data
This section demonstrates how to perform predictive analytics on product sales data using Python libraries such as Pandas, NumPy, and Scikit-learn.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# Sample product sales data
data = {
'Month': pd.date_range(start='2022-01-01', periods=12, freq='M'),
'Sales': [1500, 1600, 1700, 1800, 1750, 1900, 2100, 2200, 2300, 2400, 2500, 2600]
}
df = pd.DataFrame(data)
df['Month'] = pd.to_datetime(df['Month'])
df['Month_Num'] = df['Month'].dt.month
# Plot the historical sales data
plt.figure(figsize=(10, 6))
plt.plot(df['Month'], df['Sales'], marker='o', linestyle='-', color='blue')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Historical Sales Data')
plt.grid(True)
plt.show()
# Define features and target variable
X = df[['Month_Num']]
y = df['Sales']
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Create and train the Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions on the testing set
y_pred = model.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("Mean Squared Error:", mse)
print("R-squared:", r2)
# Forecast future sales
future_months = pd.date_range(start='2023-01-01', periods=6, freq='M')
future_months_num = future_months.month
future_sales = model.predict(future_months_num.reshape(-1, 1))
# Plot the forecasted sales
plt.figure(figsize=(10, 6))
plt.plot(df['Month'], df['Sales'], marker='o', linestyle='-', color='blue', label='Historical Sales')
plt.plot(future_months, future_sales, marker='o', linestyle='--', color='red', label='Forecasted Sales')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales Forecast')
plt.legend()
plt.grid(True)
plt.show()Output: The script generates a historical sales plot, model performance metrics (MSE and R-squared), and a visual forecast for future months.
Visualization Techniques and Map Types
Learn to implement various visualization techniques, including Bar Charts, Column Charts, Line Charts, Scatter Plots, and 3D Cubes using Matplotlib.
Python Visualization Program
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Sample data for bar and column charts
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Sample data for line chart and scatter plot
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Sample data for 3D plot
z = [1, 4, 9, 16, 25]
# Plotting Bar Chart
plt.figure(figsize=(14, 10))
plt.subplot(2, 2, 1)
plt.bar(categories, values, color='blue')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
# Plotting Column Chart
plt.subplot(2, 2, 2)
plt.bar(categories, values, color='green')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Column Chart')
# Plotting Line Chart
plt.subplot(2, 2, 3)
plt.plot(x, y, marker='o', linestyle='-', color='red')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Chart')
# Plotting Scatter Plot
plt.subplot(2, 2, 4)
plt.scatter(x, y, color='purple')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.tight_layout()
plt.show()
# Plotting 3D Plot
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, color='orange')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Scatter Plot')
plt.show()Output: The program displays a 2×2 grid of 2D charts followed by a separate window for the 3D scatter plot.
