Dual Axes Visualization

Given a dataset representing monthly sales (in thousands) and advertising expenses (in hundreds) over a year, plot a line chart with dual y-axes showcasing the relationship between the two series.

Example Output:

Use twinx() to create a second y-axis on the same plot.

import matplotlib.pyplot as plt

def dual_axes_plot(monthly_sales, advertising_expenses):
    months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    fig, ax1 = plt.subplots()

    color = 'tab:blue'
    ax1.set_xlabel('Months')
    ax1.set_ylabel('Sales (in thousands)', color=color)
    ax1.plot(months, monthly_sales, color=color)
    ax1.tick_params(axis='y', labelcolor=color)

    ax2 = ax1.twinx()
    color = 'tab:red'
    ax2.set_ylabel('Advertising Expenses (in hundreds)', color=color)
    ax2.plot(months, advertising_expenses, color=color)
    ax2.tick_params(axis='y', labelcolor=color)

    plt.title("Monthly Sales and Advertising Expenses Over a Year")
    plt.show()

# Example usage
sales = [50, 55, 60, 65, 70, 80, 90, 85, 80, 75, 70, 60]
expenses = [5, 5.5, 6, 6.5, 7, 8, 9, 8.5, 8, 7.5, 7, 6]
dual_axes_plot(sales, expenses)

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!