Compare Sales Across Regions Using Subplots
Description:
A Python program that compares sales across different regions using multiple subplots in a single figure with matplotlib
.
Code Explanation:
• Imports matplotlib.pyplot
for plotting.
• Defines sales data for four regions (North
, South
, East
, and West
) across four months (Jan
, Feb
, Mar
, Apr
).
• Creates a 2x2 subplot layout using plt.subplots()
, with each subplot displaying data for a different region.
• For each subplot, uses axes[row, col].plot()
to plot the sales data for that region over the months.
• Sets titles, X and Y labels for each subplot to clarify the data.
• Uses plt.tight_layout()
to adjust spacing between subplots automatically for a cleaner presentation.
• Finally, plt.show()
displays the figure with all subplots.
Program:
import matplotlib.pyplot as plt
# Sample sales data
regions = ['North', 'South', 'East', 'West']
sales = {
'North': [1200, 1400, 1600, 1800],
'South': [900, 1100, 1300, 1500],
'East': [800, 1000, 1200, 1400],
'West': [700, 900, 1100, 1300]
}
months = ['Jan', 'Feb', 'Mar', 'Apr']
# Create subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# Plot data for each region in a separate subplot
axes[0, 0].plot(months, sales['North'], color='blue', marker='o')
axes[0, 0].set_title('North Region')
axes[0, 0].set_xlabel('Month')
axes[0, 0].set_ylabel('Sales')
axes[0, 1].plot(months, sales['South'], color='green', marker='s')
axes[0, 1].set_title('South Region')
axes[0, 1].set_xlabel('Month')
axes[0, 1].set_ylabel('Sales')
axes[1, 0].plot(months, sales['East'], color='red', marker='^')
axes[1, 0].set_title('East Region')
axes[1, 0].set_xlabel('Month')
axes[1, 0].set_ylabel('Sales')
axes[1, 1].plot(months, sales['West'], color='purple', marker='x')
axes[1, 1].set_title('West Region')
axes[1, 1].set_xlabel('Month')
axes[1, 1].set_ylabel('Sales')
# Adjust layout
plt.tight_layout()
# Show the plot
plt.show()
Output: