Search code examples
pythonmatplotlib

How to align two plots in Matplotlib


I have the following matplotlib code

import matplotlib.pyplot as plt
import numpy as np

# Time of day values
time_of_day = [
    "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00",
    "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00",
    "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"
]

# Electricity load values in W
electricity_load = np.array([
    5460, 177, 163, 745, 770, 1049, 1090, 868, 277, 3117, 3416, 1383, 1551, 4324, 969, 431, 703, 1201, 898, 4969,7839, 259, 410, 617
])

# Convert electricity load values to kW
electricity_load_kW = electricity_load / 1000

# Price values in Cent/kWh
price_values = [
    27.1,  26.5,  26.0, 25.1, 26.6, 27.5,  34.4, 51.3, 45.3,  44.3, 44.3,  41.3,  38.1,  35.5,
    33.9,  37, 41.4,  48.6,  53.4,  48.6,  43.4, 38.7, 37.8,  27.4,
]

# Create subplots within the same figure
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), sharex=True)

# Plotting the bar diagram
ax1.bar(time_of_day, electricity_load_kW[:len(time_of_day)], color='#FFD700', edgecolor='black')

# Labeling the first plot
ax1.set_ylabel('Electricity Load (kW)', fontsize=18)
ax1.grid(axis='y', linestyle='--', alpha=0.7)

# Plotting the step line plot
ax2.step(time_of_day, price_values, where='post', color='limegreen', linewidth=6)

# Labeling the second plot
ax2.set_xlabel('Time of Day', fontsize=18)
ax2.set_ylabel('Price (Cent/kWh)', fontsize=18)
ax2.grid(axis='y', linestyle='--', alpha=0.7)

# Adjust x-axis limits to eliminate empty space
ax1.set_xlim(time_of_day[0], time_of_day[-1])

# Increase thickness and rotation of x-tick labels
for ax in [ax1, ax2]:
    ax.tick_params(axis='x', which='both', labelsize=14, width=2)

# Set x-tick labels with rotation and horizontal alignment
plt.sca(ax1)
plt.xticks(rotation=45, ha='right')

plt.sca(ax2)
plt.xticks(rotation=45, ha='right')

# Tighten the layout
plt.tight_layout()

# Save the figure and plot it
plt.savefig('C:/Users/wi9632/Desktop/temp_combined.png', dpi=100)
plt.show()

So I have a bar diagram on the upper part and on the lower part there is a step line plot. What I want is that the horizontal lines of the bar diagram and the step line plot are at the same x-position such that they are aligned. This means that the values for the x-label ticks (00:00 to 01:00, 01:00 to 02:00 etc.) should be at the same position which is currently not the case.


Solution

  • I suggest you to center the bar plot on edge:

    # Plotting the bar diagram
    ax1.bar(time_of_day, electricity_load_kW[:len(time_of_day)], color='#FFD700', edgecolor='black', align='edge', width=1)
    

    This gives the following plot (I hope this is what you were searching for):

    enter image description here