Azad Rasul



Create a plot with dual y-axes in Python

Create a plot with dual y-axes in Python

Azad Rasul's photo
Azad Rasul
·Mar 4, 2023·

1 min read

Play this article
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

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

Image description

Share this