Matplotlib: Trouble with Creating a Multi-Axis Plot with Different Y-axis Scales
I'm not sure how to approach I'm struggling to create a multi-axis plot using Matplotlib where each y-axis has its own scale... I want to visualize two different datasets (temperature and precipitation) on the same x-axis (months), but they are on completely different scales, making it hard to interpret the data. I've tried using `twinx()` to create a second y-axis, but the alignment seems off, and the ticks are overlapping, making the plot unreadable. Here's a simplified version of what I've attempted: ```python import matplotlib.pyplot as plt import numpy as np # Sample data months = np.arange(1, 13) temperature = np.random.normal(20, 5, 12) # Degrees Celsius precipitation = np.random.normal(100, 30, 12) # mm fig, ax1 = plt.subplots() # First y-axis for temperature ax1.plot(months, temperature, color='r', label='Temperature') ax1.set_ylabel('Temperature (Β°C)', color='r') ax1.tick_params(axis='y', labelcolor='r') # Second y-axis for precipitation ax2 = ax1.twinx() ax2.plot(months, precipitation, color='b', label='Precipitation') ax2.set_ylabel('Precipitation (mm)', color='b') ax2.tick_params(axis='y', labelcolor='b') # Add x-axis labels ax1.set_xticks(months) ax1.set_xticklabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']) plt.title('Temperature and Precipitation over 12 Months') plt.show() ``` After running this code, the lines are plotted, but I canβt seem to get the ticks on both y-axes to be aligned properly. The temperature line is very close to the top of the figure, while the precipitation line is almost at the bottom. Is there a way to improve the alignment and ensure that the ticks do not overlap? I've also checked that I'm using Matplotlib version 3.4.3. Any help would be greatly appreciated! I'm using Python 3.10 in this project. Any examples would be super helpful.