Create a plot with dual y-axes in Python

Create a plot with dual y-axes in Python

·

3 min read

Table of contents

No heading

No headings in the article.

Learn how to create a plot with dual y-axes in Python using the Matplotlib library. This technique enables you to visualize two sets of data with different units or scales on the same plot, making it easier to compare and contrast them. With the help of the twinx() function, you can create a second y-axis that corresponds to the second set of data. Follow the step-by-step guide in this article to create your own dual y-axis plot in Python.

Import library:

import matplotlib.pyplot as plt

Create some data:

# Data
years = [2015, 2016, 2017, 2018, 2019]
percentage = [float('NaN'), 3.31, 3.92, 2.79, 2.34]
n_students = [28099, 29030, 30167, 31008, 31733]

Create figure and axes:

fig, ax1 = plt.subplots(figsize=(8, 6))

Plot percentage on left axis:

ax1.plot(years, percentage, color='blue', marker='o', label='Population Growth')
ax1.set_ylabel('Population Growth', color='blue', fontsize=12)
ax1.tick_params(axis='y', labelcolor='blue', labelsize=10)
ax1.set_ylim([0, 5])  # set the y-axis limit to start from 0
ax1.set_xlabel("Year", fontsize=12)

Create a twin axes object on the right:

ax2 = ax1.twinx()

Plot the number of students on the right axis:

ax2.plot(years, n_students, color='red', marker='s', label='Number of Population')
ax2.set_ylabel('Number of Population', color='red', fontsize=12)
ax2.tick_params(axis='y', labelcolor='red', labelsize=10)
ax2.set_ylim([27000, 32500])  # set the y-axis limit to show the values better

Set title and labels:

plt.title('', fontsize=14, fontweight='bold')
ax1.set_xticks(years)  # set the x-ticks to the years
ax1.set_xticklabels(years, fontsize=10)  # set the x-tick labels to the years

Add legend:

lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines + lines2, labels + labels2, loc='upper left', fontsize=10)

Add grid:

plt.grid(linestyle='--')

Show the plot:

plt.show()

Save the plot as a PNG image:

plt.savefig('timeline_Shaqlawa_Population.png', dpi=300, bbox_inches='tight')

Overall the code is:

import matplotlib.pyplot as plt

# Data
years = [2015, 2016, 2017, 2018, 2019]
percentage = [float('NaN'), 3.31, 3.92, 2.79, 2.34]
n_students = [28099, 29030, 30167, 31008, 31733]

# Create figure and axes
fig, ax1 = plt.subplots(figsize=(8, 6)) 

# Plot percentage on left axis
ax1.plot(years, percentage, color='blue', marker='o', label='Population Growth')
ax1.set_ylabel('Population Growth', color='blue', fontsize=12)
ax1.tick_params(axis='y', labelcolor='blue', labelsize=10)
ax1.set_ylim([0, 5])  # set the y-axis limit to start from 0
ax1.set_xlabel("Year", fontsize=12)

# Create a twin axes object on the right
ax2 = ax1.twinx()

# Plot number of students on right axis
ax2.plot(years, n_students, color='red', marker='s', label='Number of Population')
ax2.set_ylabel('Number of Population', color='red', fontsize=12)
ax2.tick_params(axis='y', labelcolor='red', labelsize=10)
ax2.set_ylim([27000, 32500])  # set the y-axis limit to show the values better

# Set title and labels
plt.title('', fontsize=14, fontweight='bold')
ax1.set_xticks(years)  # set the x-ticks to the years
ax1.set_xticklabels(years, fontsize=10)  # set the x-tick labels to the years

# Add legend
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines + lines2, labels + labels2, loc='upper left', fontsize=10)

# Add grid
plt.grid(linestyle='--')

# Show the plot
plt.show()
# Save the plot as a PNG image
#plt.savefig('timeline_Shaqlawa_Population.png', dpi=300, bbox_inches='tight')

Image description

In conclusion, it is possible to create a plot with dual y-axes in Python using the Matplotlib library. This can be achieved by using the twinx() function to create a second y-axis and then plotting the second set of data on it. The resulting plot will have two y-axes, one on the left and one on the right, with each corresponding to a different set of data. This can be useful for visualizing data with different units or scales on the same plot.

Did you find this article valuable?

Support SmartRS by becoming a sponsor. Any amount is appreciated!