Stacked Bar Charts

Given a dataset showcasing sales of three different products over a year, plot a stacked bar chart representing the sales. Ensure each product has a distinct color and the x-axis labels showcase months.

 

Example Output:

Use Matplotlib’s bar method and provide the bottom parameter for stacking.

import matplotlib.pyplot as plt
import numpy as np

def stacked_bar_chart(product1, product2, product3):
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    plt.bar(months, product1, label="Product 1", color='red')
    plt.bar(months, product2, bottom=product1, label="Product 2", color='green')
    plt.bar(months, product3, bottom=np.array(product1)+np.array(product2), label="Product 3", color='blue')
    plt.xlabel("Months")
    plt.ylabel("Sales")
    plt.title("Sales of Products Over a Year")
    plt.legend()
    plt.grid(axis='y')
    plt.show()

# Example usage
product1_sales = [5000, 6000, 6500, 6100, 7000, 7100, 7200, 7500, 7300, 7800, 8000, 8200]
product2_sales = [4500, 4800, 5100, 5400, 5200, 5600, 5700, 5900, 6000, 6200, 6300, 6400]
product3_sales = [7000, 7100, 7200, 7300, 7400, 7500, 7600, 7700, 7900, 8000, 8100, 8200]
stacked_bar_chart(product1_sales, product2_sales, product3_sales)

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!