# Matplotlib secondary y-axis [Complete Guide]

In this Python tutorial, we’ll discuss Matplotlib secondary y-axis in python. Here we will cover different examples related to the secondary y-axis using matplotlib. And we’ll also cover the following topics:

• Matplotlib secondary y-axis limits
• Matplotlib secondary y-axis label
• Matplotlib secondary y-axis log scale
• Matplotlib secondary y-axis color
• Matplotlib secondary y-axis align 0
• Matplotlib secondary y-axis subplot
• Matplotlib secondary y-axis histogram
• Matplotlib scatter secondary y-axis
• Matplotlib secondary y-axis ticks
• Matplotlib second y-axis pandas

## Matplotlib secondary y-axis limits

Here we’ll learn to set the axes limits of the secondary y-axis using matplotlib. In matplotlib, we have different functions for setting up the axes limits.

The functions are as follow:

• ylim() function
• set_ylim() function
• axis() function

Now, let’s see different examples related to this:

Example #1

Here, we are going to plot a graph with the secondary y-axis and then set its limit using the ylim() function.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(200)
y = np.cos(x)

# Plot Graph

fig, ax1 = plt.subplots()
ax1.plot(x, y)

# Define Labels

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis')

# Twin Axes

ax2 = ax1.twinx()
ax2.set_ylabel('Y2-axis')

# Set limit

plt.ylim(-1, 1)

# Display

plt.show()
``````
• Firstly, import necessary libraries such as matplotlib.pyplot, and numpy.
• Next, define the data coordinates using arange() and cos() function of numpy.
• Then, use a subplot() function that returns the tuple containing the figure and axes object.
• Plot a graph corresponding to axes 1 object by using the plot() function.
• Define the labels of axes 1, using set_xlabel() and set_ylabel() function.
• Then, create a secondary y-axis by using the twinx() function.
• To set the label at the secondary y-axis, use the set_ylabel() function.
• Then, use the plt.ylim() function to set the axis limit of the secondary y-axis.
• To display the graph, use the show() function.

Note: Use the ylim() function after the twinx() function or after the secondary y-axis axes object. If you, use this function anywhere else it will change the limits of the primary y-axis.

Example #2

Here we are going to plot a graph with the secondary y-axis and then set its limit using the set_ylim() function.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(50)
y = np.sin(x)

# Plot Graph

fig, ax1 = plt.subplots()
ax1.plot(x, y)

# Define Labels

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis')

# Twin Axes

ax2 = ax1.twinx()
ax2.set_ylabel('Y2-axis')

# Set limit

ax2.set_ylim(-1, 1)

# Display

plt.show()``````
• Import numpy library for data creation.
• Import matplotlib.pyplot library for data visualization.
• Define x and y coordinates, using arange() and sin() function of numpy.
• Then, use a subplot() function that returns the tuple containing the figure and axes object.
• Plot the graph using the plot() function of axes 1 object.
• Then use the set_xlabel() and set_ylabel() function to add label at axes.
• Use twinx() function to create secondary y-axis.
• To set the limit of the secondary y-axis, use the set_ylim() function corresponding to the secondary y-axis object.
• To display the graph, use the show() function.

Example #3

Here we are going to plot a graph with the secondary y-axis and then set its limit using the axis() function.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(50)
y = np.cos(x*50)

# Plot Graph

fig, ax1 = plt.subplots()
ax1.plot(x, y)

# Define Labels

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y1-axis')

# Twin Axes

ax2 = ax1.twinx()
ax2.set_ylabel('Y2-axis')

# Set limit

plt.axis([None, None, -1, 1])

# Display

plt.show()``````
• Import numpy and matplotlib.pyplot libraries.
• Next, define the data coordinates.
• To plot the graph, use the plot() function corresponding to axis 1 object.
• To create a secondary y-axis, use the twinx() function.
• To set the limit of the secondary y-axis, we use plt.axis() function. Here we set xmin and xmax values to None as we don’t want to change the limit of the x-axis.

Note: Use the axis() function after the twinx() function or after the secondary y-axis axes object. If you, use this function anywhere else it will change the limits of the primary y-axis.

Also, check: What is add_axes matplotlib

## Matplotlib secondary y-axis label

Here we’ll learn to add a label at the secondary y-axis using matplotlib. We can use ylabel() function or set_ylabel() function to add label at y-axis.

Let’s see examples related to this:

Example #1

In this example, we add a label at the secondary y-axis by using ylabel() method.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.sin(x)
data_2 = np.exp(x)

# Create Plot

fig, ax1 = plt.subplots()

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary-axis')
ax1.plot(x, data_1, color = 'red')

ax2 = ax1.twinx()
ax2.plot(x, data_2, color = 'blue')

plt.ylabel('Secondary-axis')

# Show plot

plt.show()``````
• Import necessary libraries such as numpy and matplotlib.pyplot.
• To define data coordinates, use arange(), sin(), and exp() function of numpy.
• Then, use a subplots() function that returns the tuple containing the figure and axes 1 object.
• After this, add label at x-axis and primary y-axis, use set_xlabel() and set_ylabel() function corresponding to axes object 1.
• Then, create secondary y-axis by using twinx() function.
• To plot a graph, use plot() function.
• To add a label at secondary y-axis, use ylabel() function. Take care of one thing function must be defined after creation of axes object 2.
• To display the graph, we use show() function.

Example #2

In this example, we add a label at the secondary y-axis by using the set_ylabel() method.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.sin(x)
data_2 = np.exp(x)

# Create Plot

fig, ax1 = plt.subplots()

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary-axis')
ax1.plot(x, data_1, color = 'red')

ax2 = ax1.twinx()
ax2.plot(x, data_2, color = 'blue')

plt.ylabel('Secondary-axis')

# Show plot

plt.show()``````
• Import necessary libraries such as numpy and matplotlib.pyplot.
• Next, we use arange(), sin(), and exp() function to define data coordinates.
• To create second y-axis, use twinx() function.
• To plot the graph, use plot() function.
• To add a label at secondary y-axis, we use set_ylabel() function corresponding to twin axes object.

## Matplotlib secondary y-axis log scale

Here we’ll learn to create a secondary y-axis with log scale using matplotlib.

Let’s see an example:

``````# Import libraries

import matplotlib.pyplot as plt
import numpy as np

# Set figure size

fig = plt.figure(figsize=(6,5))

# Create subplot

# Create secondary axes

ax2 = ax.twinx()

# Define Data

x = np.random.rand(50)
y = np.random.rand(50)
y2 = data = [10**i for i in range(50)]

# Plot graph

ax.scatter(x, y, c="b")
ax2.scatter(x, y2, c="r")

# Set second y-axis to log

ax2.set_yscale("log")

ax.set_ylabel("Linear axis")
ax2.set_ylabel("Logarithmic axis")

# Display

plt.show()``````
• Import matplotlib.pyplot library.
• Import numpy library for data creation.
• To set the figure size, use figure() method and pass figsize parameter to the method to set width and height of the plot.
• Then, use a add_subplot() function corresponding to axes 1 object.
• After this, create secondary y-axis corresponding to axes 2 object.
• To define data coordinates, use random.rand() function and for loop and range() function.
• To plot the scatter graph, use scatter() function.
• Now, set secondary y-axis in log scale form by using set_yscale() function.
• To set labels at primary and secondary y-axes, we use set_ylabel() function with corresponding axes.
• To display the graph, use the show() function.

## Matplotlib secondary y-axis color

Here we set the color of the secondary y-axis using matplotlib.

Let’s see an example:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(0, 15, 0.2)
data_1 = np.sin(x)
data_2 = np.cos(x)

# Create Plot

fig, ax1 = plt.subplots()

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary-axis')
ax1.plot(x, data_1, color = 'red')

ax2 = ax1.twinx()
ax2.plot(x, data_2, color = 'blue')

ax2.set_ylabel('Secondary Y-axis', color= 'blue')
ax2.tick_params(axis='y', color='blue', labelcolor='blue')

# Show plot

plt.show()``````
• Import numpy and matplotlib.pyplot libraries.
• Next, define data coordinates using arange(), sin(), and cos() function of numpy.
• Create subplot by using subplots() function corresponding to axes object 1.
• Then we add label at x-axis and primary y-axis, by using set_xlabel() and set_ylabel() function.
• To plot the graph, we use the plot() function.
• To create a second y-axis, we use the twinx() function.
• To add a label at secondary y-axis, we use the set_ylabel() function.
• To set the same color of the axes label as plotting line pass color parameter to set_ylabel() method.
• To set the same color of the ticks and ticks label as plotting line pass color and labelcolor parameter to the tick_params() method.

## Matplotlib secondary y-axis align 0

Here we’ll learn to align the secondary y-axis to 0 using matplotlib with the example. To align the axis to 0 we set the bottom of the y-axis to 0.

Syntax:

``matplotlib.pyplot.ylim(bottom=0)``

You can also use set_ylim() or axis() function instead of ylim().

Let’s see an example:

Here we are going to use set_ylim() function to align the secondary y-axis to 0.

``````# Import Library

import pandas as pd

# Create DataFrames

df1 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'profit': [80, 60, 50, 95, 75, 63, 35, 90,
68, 78]})

df2 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'loss': [20, 40, 50, 5, 25, 37, 65, 10, 32,
22]})

# Print

print(df1)
print('\n')
print(df2)``````
• To create a Data Frame, we first need to import a pandas library.
• We generate data frames with the DataFrame() method.
• After that, we display both data frames by using the print() function.
``````# Import Library

import matplotlib.pyplot as plt

# define subplots

fig,ax = plt.subplots()

# plot

ax.plot(df1.year, df1.profit, color='slategrey', marker='o',
linewidth=3)

ax.set_xlabel('Year')

ax.set_ylabel('Profit')

# define second y-axis

ax2 = ax.twinx()

# plot

ax2.plot(df2.year, df2.loss, color='orange', marker ='o',
linewidth=3)

# Align to 0

ax2.set_ylim(bottom=0)

ax2.set_ylabel('Loss')

# Display

plt.show()``````
• For data visualization, import the matplotlib.pyplot library.
• Create a subplot by calling the subplots() function on the axis object.
• The plot() function is used to create a line chart.
• We also pass color, marker, and linewidth as parameters to enhance the plot.
• The set_xlabel() function is used to set the label on the x-axis.
• The set_ylabel() function is used to set the label on the primary y-axis.
• We use the set_ylim() function with the bottom argument set to 0 to align the secondary axis to 0.
• The set_ylabel() function, which corresponds to axes object 2, is used to set the label on the secondary y-axis.
• The show() function is used to display the graph.

## Matplotlib secondary y-axis subplot

In this matplotlib tutorial, we’ll learn how to share the secondary Y-axis between subplots.

Let’s see examples related to this:

Example #1

Here we add a secondary y-axis to the specific subplot.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

x = np.arange(20)
y = np.cos(x*60)

# Define Subplot

fig, ax = plt.subplots(2, figsize=(8,6))

# Plot

ax[0].plot(x, y)

# Define Labels

ax[0].set_xlabel('X-axis')
ax[0].set_ylabel('Y-axis')

# Twin Axes

ax1 = ax[1].twinx()

# Plot

ax[1].plot(x,y)

ax[1].set_ylabel('Primary Y-axis')
ax1.set_ylabel('Secondary Y-axis')

# Display

plt.show()``````
• Import numpy library for data creation.
• Import matplotlib.pyplot library for data visualization.
• To define the data coordinates, use arange(), and cos() method of numpy.
• After this, create subplot using subplots() method.
• Then plot the line graph, using plot() function.
• To set the axes label, use set_xlabel(), and set_ylabel() method.
• To create twin y-axis in second plot, use twinx() function.
• ax1.set_ylabel() function is used to add secondary y-axis label.
• To display the figure, we use show() method.

## Matplotlib secondary y-axis histogram

Here we’ll learn to create a histogram with two y-axes using matplotlib.

Let’s see an example:

``````# Import Libraries

import matplotlib.pyplot as plt
import numpy as np

# Define subplot

fig, ax = plt.subplots()

# Initialize the random number generator

np.random.seed(100)

# Define Data

data = np.random.randn(1000)

# Create histogram

ax.hist(data, bins=40)

# Second y-axis

ax2 = ax.twinx()

# Create histogram

ax2.hist(data, bins=40, density=True, cumulative=True,
histtype="step", color="lime")

# Display

plt.show()``````
• Import numpy library for data creation.
• Import matplotlib.pyplot for data visualization.
• Then, use a subplot() function that returns the tuple containing the figure and axes object.
• The random number generator is then initialised using the seed() method. To generate a random number, the random number generator requires a starting value known as seed value.
• The random.rand() function is then used to generate an array with the required shape and random values.
• Create histogram using hist() function.
• Next, create second y axis using twinx() function.
• Then create histogram corresponding to twinx, using hist() function.
• Then we pass the following parameters to the hist() function to glorify the plot
• density: specify the density of the bins.
• cumulative: If True, a histogram is created, with each bin containing the counts in that bin as well as all bins for smaller values. The entire number of datapoints is shown in the last bin.
• hisstype: It set the type of histogram .We set it to step, which generates a line plot.
• color: Specify the color.

## Matplotlib scatter secondary y-axis

Here we’ll learn to create scatter with two y-axes using matplotlib.

Let’s see an example:

Here we create a scatter plot with two y-axes.

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Define Data

name = ['Ava', 'Noah', 'Charlotte', 'Robert', 'Patricia']
weight_kg = [45, 60, 50, 75, 53]
height_cm = [162, 175, 155, 170, 168]

# Create Plot

fig, ax1 = plt.subplots()

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary Y-axis')
ax1.scatter(name, weight_kg ,color = 'red')

ax2 = ax1.twinx()
ax2.scatter(name, height_cm, color = 'blue')

# Add label at second y-axis

ax2.set_ylabel('Secondary Y-axis')

# Show plot

plt.show()``````
• Import the required libraries, namely numpy and matplotlib.pyplot.
• After that, you must define the data coordinates for plotting.
• Then use the subplots() function to get a tuple with the figure and axes objects.
• Use the set_xaxis() function to add a label to the x-axis.
• The set_yaxis() function was used to add labels to the primary and secondary y-axes, respectively.
• Use the scatter() method to create a scatter graph.
• Use the show() function to display the plot.

## Matplotlib secondary y-axis ticks

Here we’ll learn to set ticks at the secondary y-axis using matplotlib with the help of an example.

Let’s see examples:

``````# Import Library

import numpy as np
import matplotlib.pyplot as plt

# Subplot

fig, ax1 = plt.subplots()

# Define Data

x = np.linspace(0, 5 * np.pi, 150)
data_1 = np.sin(x)
data_2 = np.cos(x)

# Create Plot

ax1.set_xlabel('X-axis')
ax1.set_ylabel('Primary-axis')
ax1.plot(x, data_1,color='r')

ax2 = ax1.twinx()
ax2.plot(x, data_2)

# Set y axis ticks and labels

ax2.set_yticks([-1,0, 1, 2, 3, 4])
ax2.set_yticklabels(['Label-1', 'Label-2', 'Label-3',
'Label-4', 'Label-5', 'Label-6'])

ax2.set_ylabel('Second Y-axis')

# Show plot

plt.show()``````
• Import numpy library for data creation.
• Import matplotlib.pyplot library as plt for data visualization.
• Then use the subplots() function to get a tuple with the figure and axes objects.
• After this, we create data coordinates using numpy functions namely linspace(), sin(), and cos().
• To add labels at axes, use set_xlabel() and set_ylabel() function.
• To plot a graph, we use plot() function.
• To create second y-axis, use twinx() function.
• To fix the position of ticks at the y-axis, we use the set_yticks() function.
• To set the string labels at the y-axis, we use the set_yticklabels() functions.

## Matplotlib second y-axis pandas

Here we’ll learn to add second y-axis using pandas DataFrame in matplotlib.

Let’s see an example:

``````# Import Libraries

import pandas as pd
import matplotlib.pyplot as plt

# Creating dataframe for plot

df1 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'profit': [80, 60, 50, 95, 75, 63, 35, 90,
68, 78]})

df2 = pd.DataFrame({'year': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'loss': [20, 40, 50, 5, 25, 37, 65, 10, 32,
22]})

# Creating axes object and defining plot

ax = df1.plot(kind = 'line', x = 'year',
y = 'profit', color = 'slategrey', marker='o')

ax2 = df2.plot(kind = 'line', x = 'year',
y = 'loss', secondary_y = True,
color = 'Red', marker = 'o',
ax = ax)

# Labeling axes

ax.set_xlabel('Year')
ax.set_ylabel('Profit')
ax2.set_ylabel('Loss')

# Show plot

plt.show()``````
• Import pandas library for creating DataFrame.
• Import matplotlib.pyplot library for data visualization.
• After this, create dataframes for plot by using DataFrame() function of pandas.
• Then, create axes objects and define plot, using plot() function.
• To plot data on a secondary y-axis, use the secondary_y keyword in df2.plot() method.
• To label the axes, we use set_xlabel() and set_ylabel() function in respective to their axes object.
• To display the graph, use show() function.

You may also like to read the following tutorials on Matplotlib.

So, in this Python tutorial, we have discussed the “Matplotlib secondary y-axis” and we have also covered some examples related to using the secondary y-axis. These are the following topics that we have discussed in this tutorial.

• Matplotlib secondary y-axis limits
• Matplotlib secondary y-axis label
• Matplotlib secondary y-axis log scale
• Matplotlib secondary y-axis color
• Matplotlib secondary y-axis align 0
• Matplotlib secondary y-axis subplot
• Matplotlib secondary y-axis histogram
• Matplotlib scatter secondary y-axis
• Matplotlib secondary y-axis ticks
• Matplotlib second y-axis pandas