Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Dual Axis Plots

Learn how to create plots with two different axes using Matplotlib. Understand twinx(), twiny(), multiple scales, legends, and axis formatting.

1. Introduction to Dual Axis Plots

A dual axis plot is a chart that contains two axes for displaying different datasets. It is useful when two datasets have different measurement units or different value ranges.

For example, a company may want to display monthly sales and profit in the same chart. Sales may be measured in thousands of rupees, while profit may be measured as a percentage.

Using only one Y-axis may make one dataset difficult to understand. A second Y-axis allows both datasets to be displayed together.

Common Use Cases

  • Temperature and rainfall comparison.
  • Sales amount and profit percentage.
  • Website visitors and conversion rate.
  • Stock price and trading volume.
  • Revenue and customer growth.

2. Types of Dual Axis Plots

Matplotlib provides two important methods for creating a second axis: twinx() and twiny().

Method Shared Axis Independent Axis Second Axis Position
twinx() X-axis Y-axis Right side
twiny() Y-axis X-axis Top side
Primary Y-axis Secondary Y-axis Shared X-axis Conceptual illustration of a twinx() chart

A conceptual representation of two datasets sharing one X-axis with separate Y-axes.

3. Creating a Second Y-axis Using twinx()

The twinx() method creates another Axes object that shares the X-axis of the original Axes but has an independent Y-axis.

The second Y-axis appears on the right side of the chart. Both axes use the same X-axis values, making it useful for comparing two measurements over the same categories or time periods.

Syntax

ax2 = ax1.twinx()

Here, ax1 is the primary Axes object and ax2 is the secondary Axes object.

Basic Example

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]

temperature = [22, 25, 28, 32, 35, 34]
rainfall = [10, 20, 35, 50, 65, 45]

fig, ax1 = plt.subplots()

# First Y-axis
ax1.plot(
    months,
    temperature,
    color="blue",
    marker="o",
    label="Temperature"
)

ax1.set_xlabel("Months")
ax1.set_ylabel("Temperature (°C)", color="blue")
ax1.tick_params(axis="y", labelcolor="blue")

# Second Y-axis
ax2 = ax1.twinx()

ax2.plot(
    months,
    rainfall,
    color="red",
    marker="s",
    label="Rainfall"
)

ax2.set_ylabel("Rainfall (mm)", color="red")
ax2.tick_params(axis="y", labelcolor="red")

ax1.set_title("Monthly Temperature and Rainfall")

ax1.grid(True, alpha=0.3)

plt.show()

Output

Chart Title: Monthly Temperature and Rainfall

X-axis:
Months

Left Y-axis:
Temperature (°C)
Colour: Blue

Right Y-axis:
Rainfall (mm)
Colour: Red

Temperature and rainfall are displayed
using two separate Y-axes.
Tip: Use different colours for the two datasets and their corresponding Y-axis labels. This makes it easier for readers to understand which line belongs to which scale.

4. Formatting Both Y-axes

When creating a dual Y-axis chart, both axes should have meaningful labels, suitable colours, and appropriate limits.

Setting Axis Labels and Colours

ax1.set_ylabel("Sales (₹)", color="blue")
ax2.set_ylabel("Profit (%)", color="green")

ax1.tick_params(axis="y", labelcolor="blue")
ax2.tick_params(axis="y", labelcolor="green")

Setting Different Y-axis Limits

ax1.set_ylim(0, 100000)
ax2.set_ylim(0, 100)

The primary axis can display sales values from zero to one lakh, while the secondary axis can display profit percentages from zero to one hundred.

Complete Sales and Profit Example

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May"]

sales = [25000, 30000, 42000, 50000, 65000]
profit = [12, 15, 18, 20, 25]

fig, ax1 = plt.subplots(figsize=(9, 5))

line1, = ax1.plot(
    months,
    sales,
    color="blue",
    marker="o",
    label="Sales"
)

ax1.set_xlabel("Months")
ax1.set_ylabel("Sales (₹)", color="blue")
ax1.tick_params(axis="y", labelcolor="blue")
ax1.set_ylim(0, 80000)

ax2 = ax1.twinx()

line2, = ax2.plot(
    months,
    profit,
    color="green",
    marker="s",
    label="Profit"
)

ax2.set_ylabel("Profit (%)", color="green")
ax2.tick_params(axis="y", labelcolor="green")
ax2.set_ylim(0, 35)

ax1.set_title("Monthly Sales and Profit")

ax1.legend(
    handles=[line1, line2],
    labels=["Sales", "Profit"],
    loc="upper left"
)

ax1.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Output

Chart Title: Monthly Sales and Profit

Month     Sales (₹)     Profit (%)
Jan       25000         12
Feb       30000         15
Mar       42000         18
Apr       50000         20
May       65000         25

Blue line:
Monthly Sales

Green line:
Monthly Profit

Left axis:
Sales in Rupees

Right axis:
Profit in Percentage

5. Combining Legends from Both Axes

Each Axes object maintains its own legend information. When using twinx(), calling ax1.legend() alone normally displays only the artists belonging to the primary Axes.

To display both datasets in one legend, collect the handles and labels from both axes and pass them to the primary legend.

Using get_legend_handles_labels()

handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()

ax1.legend(
    handles1 + handles2,
    labels1 + labels2,
    loc="upper left"
)

This approach combines the legend entries from the primary and secondary Axes objects.

Complete Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
temperature = [20, 24, 27, 30, 33]
humidity = [60, 55, 50, 45, 40]

fig, ax1 = plt.subplots()

ax1.plot(
    x,
    temperature,
    color="blue",
    marker="o",
    label="Temperature"
)

ax1.set_xlabel("Day")
ax1.set_ylabel("Temperature (°C)", color="blue")

ax2 = ax1.twinx()

ax2.plot(
    x,
    humidity,
    color="red",
    marker="s",
    label="Humidity"
)

ax2.set_ylabel("Humidity (%)", color="red")

handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()

ax1.legend(
    handles1 + handles2,
    labels1 + labels2,
    loc="upper right"
)

ax1.set_title("Temperature and Humidity")

plt.show()

Output

Combined Legend:

Blue line  - Temperature
Red line   - Humidity

Both datasets appear in one legend.
Tip: Combining legend handles is useful when you want one clear legend instead of separate legends for each axis.

6. Creating a Second X-axis Using twiny()

The twiny() method creates another Axes object that shares the Y-axis of the original Axes but has an independent X-axis.

The secondary X-axis is displayed at the top of the chart. It is useful when two datasets use different horizontal measurement scales but can be compared against the same vertical values.

Syntax

ax2 = ax1.twiny()

Basic Example

import matplotlib.pyplot as plt

height = [150, 160, 170, 180, 190]

weight_a = [45, 52, 60, 68, 75]
weight_b = [48, 56, 64, 72, 80]

fig, ax1 = plt.subplots()

ax1.plot(
    weight_a,
    height,
    color="blue",
    marker="o",
    label="Group A"
)

ax1.set_xlabel("Weight of Group A (kg)", color="blue")
ax1.set_ylabel("Height (cm)")
ax1.tick_params(axis="x", labelcolor="blue")

ax2 = ax1.twiny()

ax2.plot(
    weight_b,
    height,
    color="red",
    marker="s",
    label="Group B"
)

ax2.set_xlabel("Weight of Group B (kg)", color="red")
ax2.tick_params(axis="x", labelcolor="red")

ax1.set_title("Height and Weight Comparison")

plt.show()

Output

Chart Title: Height and Weight Comparison

Shared Y-axis:
Height (cm)

Bottom X-axis:
Weight of Group A (kg)

Top X-axis:
Weight of Group B (kg)

Blue line:
Group A

Red line:
Group B
Important: With twiny(), the two X-axes have independent scales. Make sure the bottom and top axis labels clearly identify the different measurements.

7. Difference Between twinx() and twiny()

Feature twinx() twiny()
Purpose Create a second Y-axis. Create a second X-axis.
Shared axis X-axis Y-axis
Independent axis Y-axis X-axis
Second axis location Right side Top side
Common use Temperature and rainfall. Two horizontal measurement scales.

8. Grid Lines and Axes Visibility

When two Axes objects overlap, grid lines from both axes may make the chart difficult to read. In many cases, it is better to enable grid lines only on the primary Axes.

# Enable grid only on the primary Axes
ax1.grid(True, linestyle="--", alpha=0.3)

# Avoid enabling an unnecessary second grid
ax2.grid(False)

Making the Secondary Axes Background Transparent

The secondary Axes has its own background patch. When overlapping axes cause drawing or visibility problems, you can make the secondary background transparent.

ax2.patch.set_visible(False)

This allows the primary Axes background to remain visible beneath the secondary Axes. Use this when needed, especially when adding additional artists to overlapping axes.

9. Complete Practical Example

In this example, we will create a monthly weather chart showing temperature and rainfall together. Temperature will use the left Y-axis, while rainfall will use the right Y-axis.

import matplotlib.pyplot as plt

# Monthly data
months = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun"
]

temperature = [18, 21, 25, 30, 34, 32]
rainfall = [5, 10, 20, 35, 60, 80]

# Create figure and primary Axes
fig, ax1 = plt.subplots(figsize=(10, 6))

# Temperature line
line1, = ax1.plot(
    months,
    temperature,
    color="blue",
    marker="o",
    linewidth=2,
    label="Temperature"
)

ax1.set_xlabel("Month")
ax1.set_ylabel("Temperature (°C)", color="blue")
ax1.tick_params(axis="y", labelcolor="blue")
ax1.set_ylim(0, 40)

# Create secondary Y-axis
ax2 = ax1.twinx()

# Rainfall line
line2, = ax2.plot(
    months,
    rainfall,
    color="red",
    marker="s",
    linewidth=2,
    label="Rainfall"
)

ax2.set_ylabel("Rainfall (mm)", color="red")
ax2.tick_params(axis="y", labelcolor="red")
ax2.set_ylim(0, 100)

# Combine legends
ax1.legend(
    handles=[line1, line2],
    labels=["Temperature", "Rainfall"],
    loc="upper left"
)

# Chart formatting
ax1.set_title(
    "Monthly Temperature and Rainfall Comparison"
)

ax1.grid(
    True,
    linestyle="--",
    alpha=0.3
)

plt.tight_layout()
plt.show()

Output

Monthly Temperature and Rainfall Comparison

Month    Temperature (°C)    Rainfall (mm)
Jan      18                  5
Feb      21                  10
Mar      25                  20
Apr      30                  35
May      34                  60
Jun      32                  80

Primary Y-axis:
Temperature (°C)

Secondary Y-axis:
Rainfall (mm)

Legend:
Blue line - Temperature
Red line  - Rainfall

10. Best Practices for Dual Axis Plots

Recommended Practices

  • Use dual axes only when there is a meaningful reason to compare two measurements.
  • Always provide clear labels for both axes.
  • Use different colours for each dataset.
  • Set suitable limits for both axes.
  • Use a combined legend when it improves readability.
  • Keep grid lines simple and avoid unnecessary visual clutter.
  • Use units such as °C, mm, ₹, or % in axis labels.

Important Limitations

Dual-axis charts can sometimes create misleading visual impressions. Changing the scale of either Y-axis can make two lines appear more closely related or more different than they actually are.

A dual-axis chart does not prove that two datasets are correlated. If the comparison is unclear, consider using separate charts or another visualization method.

11. Practice Questions

Beginner Level

  1. What is a dual axis plot?
  2. What is the purpose of the twinx() method?
  3. What is the purpose of the twiny() method?
  4. Which axis is shared when using twinx()?

Intermediate Level

  1. Create a chart showing monthly sales and profit percentage.
  2. Display temperature and rainfall using two Y-axes.
  3. Combine legends from two Axes objects.
  4. Set different limits for the primary and secondary Y-axes.

Practical Task

Create a dual-axis chart using the following data:

Month Sales (₹) Profit (%)
January 20000 10
February 30000 15
March 45000 18
April 55000 22
May 70000 28

Your chart should include a blue sales line, a green profit line, separate Y-axis labels, and one combined legend.

Summary

Dual axis plots allow us to display two datasets with different measurement units or scales in a single chart. They are useful for comparing related information such as temperature and rainfall, sales and profit, or visitors and conversion rates.

Matplotlib provides the twinx() method to create a secondary Y-axis while sharing the X-axis. The twiny() method creates a secondary X-axis while sharing the Y-axis.

We can customize both axes independently using labels, colours, tick formatting, and axis limits. We can also combine legend handles from both axes to create one common legend.

Always use clear labels, suitable scales, and meaningful comparisons. Avoid dual-axis charts when they may confuse readers or create misleading visual impressions.