from pathlib import Path import matplotlib import matplotlib.pyplot as plt import numpy as np def celsius_to_fahrenheit(celsius): return celsius * 9 / 5 + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5 / 9 months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] temperature_c = np.array([4, 7, 12, 17, 22, 26]) fig, ax = plt.subplots(figsize=(6, 4), layout="constrained") ax.plot(months, temperature_c, marker="o", linewidth=2) ax.set_title("Average monthly temperature") ax.set_xlabel("Month") ax.set_ylabel("Temperature (deg C)") ax.set_ylim(0, 30) ax.grid(True, axis="y", alpha=0.3) secondary = ax.secondary_yaxis( "right", functions=(celsius_to_fahrenheit, fahrenheit_to_celsius) ) secondary.set_ylabel("Temperature (deg F)") output = Path("temperature-secondary-axis.png") fig.savefig(output, dpi=160) fig.canvas.draw() check_c = np.array([0, 20, 30]) check_f = celsius_to_fahrenheit(check_c) round_trip_c = fahrenheit_to_celsius(check_f) print(f"matplotlib: {matplotlib.__version__} ({matplotlib.get_backend()} backend)") print(f"primary y label: {ax.get_ylabel()}") print(f"secondary y label: {secondary.get_ylabel()}") print(f"conversion check: {check_c.tolist()} deg C -> {check_f.tolist()} deg F") print(f"round trip: {round_trip_c.tolist()} deg C") print(f"saved: {output}") print(f"bytes: {output.stat().st_size}") plt.close(fig)