How to Create a Matplotlib Plot with Two Y Axes


The easiest way to create a Matplotlib plot with two y axes is to use the twinx() function.

The following example shows how to use this function in practice.

Example: Create Matplotlib Plot with Two Y Axes

Suppose we have the following two pandas DataFrames:

import pandas as pd

#create DataFrames
df1 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                    'sales': [14, 16, 19, 22, 24, 25, 24, 24, 27, 30]})

df2 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                    'leads': [4, 4, 4, 5, 4, 5, 7, 8, 5, 3]})

Both DataFrames share the ‘year’ variable that ranges from 1 to 10, but the first DataFrame displays the total sales each year while the second DataFrame displays the total leads each year.

We can use the following code to create a Matplotlib plot that displays the sales and the leads on one chart with two y axes:

import matplotlib.pyplot as plt

#define colors to use
col1 = 'steelblue'
col2 = 'red'

#define subplots
fig,ax = plt.subplots()

#add first line to plot
ax.plot(df1.year, df1.sales, color=col1)

#add x-axis label
ax.set_xlabel('Year', fontsize=14)

#add y-axis label
ax.set_ylabel('Sales', color=col1, fontsize=16)

#define second y-axis that shares x-axis with current plot
ax2 = ax.twinx()

#add second line to plot
ax2.plot(df2.year, df2.leads, color=col2)

#add second y-axis label
ax2.set_ylabel('Leads', color=col2, fontsize=16)

Matplotlib with two y axes

The y-axis on the left side of the plot shows the total sales by year and the y-axis on the right side of the plot shows the total leads by year.

The blue line in the plot represents the total sales by year and the red line represents the total leads by year.

Feel free to use the marker and linewidth arguments to change the appearance of the lines in the chart:

import matplotlib.pyplot as plt

#define colors to use
col1 = 'steelblue'
col2 = 'red'

#define subplots
fig,ax = plt.subplots()

#add first line to plot
ax.plot(df1.year, df1.sales, color=col1, marker='o', linewidth=3)

#add x-axis label
ax.set_xlabel('Year', fontsize=14)

#add y-axis label
ax.set_ylabel('Sales', color=col1, fontsize=16)

#define second y-axis that shares x-axis with current plot
ax2 = ax.twinx()

#add second line to plot
ax2.plot(df2.year, df2.leads, color=col2, marker='o', linewidth=3)

#add second y-axis label
ax2.set_ylabel('Leads', color=col2, fontsize=16)

Notice that both lines are now wider and contain ‘o’ markers to display individual data points.

Additional Resources

The following tutorials explain how to perform other common operations in Matplotlib:

How to Adjust Axis Label Position in Matplotlib
How to Set Axis Ranges in Matplotlib
How to Set X-Axis Values in Matplotlib

2 Replies to “How to Create a Matplotlib Plot with Two Y Axes”

  1. This is really handy, just wondering how I would do them as a bar chart instead of lines? Also, is there a way to make the font of the x axis (not label but values) smaller or a different angle? My values are semi-long words.

    1. Hi Alex…You can create a **Matplotlib plot with two Y-axes as a bar chart** by using `twinx()`, just like you would for a line chart. The key difference is that you’ll use `ax.bar()` instead of `ax.plot()`.

      ### Here’s how you can do it:
      – Use `ax.bar()` for the first set of bars.
      – Use `ax2.bar()` for the second set of bars, making sure to adjust the bar positions to avoid overlap.
      – Adjust **x-axis text size and angle** using `plt.xticks(rotation=angle, fontsize=size)`.

      ### Example Code:
      “`python
      import matplotlib.pyplot as plt
      import numpy as np

      # Sample Data
      categories = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Date’, ‘Elderberry’]
      values1 = [5, 7, 3, 4, 6] # First Y-axis values
      values2 = [8, 6, 4, 7, 5] # Second Y-axis values

      x = np.arange(len(categories)) # X locations

      fig, ax = plt.subplots()

      # First Y-axis (Left)
      ax.bar(x – 0.2, values1, width=0.4, color=’blue’, label=’Dataset 1′)

      # Second Y-axis (Right)
      ax2 = ax.twinx()
      ax2.bar(x + 0.2, values2, width=0.4, color=’red’, alpha=0.6, label=’Dataset 2′)

      # Formatting
      ax.set_xticks(x)
      ax.set_xticklabels(categories, rotation=45, fontsize=10) # Adjust rotation & font size
      ax.set_ylabel(“Y-Axis 1”)
      ax2.set_ylabel(“Y-Axis 2”)
      ax.legend(loc=’upper left’)
      ax2.legend(loc=’upper right’)

      plt.show()
      “`

      ### Key Adjustments:
      – `width=0.4`: Controls bar width.
      – `x – 0.2` and `x + 0.2`: Offsets bars to avoid overlap.
      – `rotation=45, fontsize=10`: Rotates and resizes x-axis labels.

Leave a Reply

Your email address will not be published. Required fields are marked *