Instagram
youtube
Facebook
Twitter

Create a Stacked Bar Chart by Region and Product

Description:
This program generates a stacked bar chart that displays the sales data of three products across different regions. The chart helps visualize how sales are distributed across the regions, with each region represented by a stacked bar containing the sales for each product.


Code Explanation:

  • Multiple datasets are stacked on top of each other using bar().

  • X-axis represents regions or categories.

  • Each stack represents a product's contribution in that region.

  • Helps visualize the total and individual contribution.

  • legend() differentiates each stack (product).

  • xlabel(), ylabel(), and title() are added for clarity.

  • show() displays the final stacked bar chart.


Code Explanation:

import matplotlib.pyplot as plt

# X-axis labels (regions)
regions = ['North', 'South', 'East', 'West']

# Sales data for each product
product_A = [30, 40, 50, 20]
product_B = [20, 35, 25, 30]
product_C = [10, 20, 15, 25]

# Plotting the stacked bars
plt.bar(regions, product_A, label='Product A', color='skyblue')
plt.bar(regions, product_B, bottom=product_A, label='Product B', color='lightgreen')
bottom_C = [a + b for a, b in zip(product_A, product_B)]
plt.bar(regions, product_C, bottom=bottom_C, label='Product C', color='salmon')

# Adding labels and title
plt.title('Stacked Bar Chart: Sales by Region and Product')
plt.xlabel('Region')
plt.ylabel('Sales')
plt.legend()

# Show the plot
plt.show()


Output: