DEV Community

Dr. Azad Rasul
Dr. Azad Rasul

Posted on

Create a plot with dual y-axes (using twinx) in Python

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')
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)