Instagram
youtube
Facebook
Twitter

Use a Secondary Y-Axis for Revenue and Units Sold

Description:
This program plots two different data sets — revenue and units sold — on the same x-axis (products or time), but using two y-axes to handle different scales.

Code Explanation:

  • twinx() creates a second Y-axis on the right side.

  • Useful when comparing two datasets with different scales.

  • One axis can show revenue, another can show units sold.

  • Both plots share the same X-axis (like time or category).


Program:

import matplotlib.pyplot as plt

# Sample data
products = ['A', 'B', 'C', 'D', 'E']
revenue = [10000, 15000, 12000, 18000, 16000]
units_sold = [200, 250, 220, 300, 270]

# Create the figure and primary axis
fig, ax1 = plt.subplots(figsize=(8, 5))

# Plot revenue on the primary y-axis
ax1.set_xlabel('Product')
ax1.set_ylabel('Revenue', color='blue')
ax1.plot(products, revenue, color='blue', marker='o', label='Revenue')
ax1.tick_params(axis='y', labelcolor='blue')

# Create secondary y-axis for units sold
ax2 = ax1.twinx()
ax2.set_ylabel('Units Sold', color='green')
ax2.plot(products, units_sold, color='green', marker='s', linestyle='--', label='Units Sold')
ax2.tick_params(axis='y', labelcolor='green')

# Add title and grid
plt.title('Revenue and Units Sold (Dual Y-Axis)')
fig.tight_layout()
plt.grid(True)
plt.show()


Output: