Line and Bar Plot in the same graph with Error Bars

The codes to for this graph is as below, with the following keypoints:

Legend Handling: The legend is constructed from both plots (line plot & bar plot), ensuring that all data series are labeled correctly.

Plotting Order: The bar plot is drawn first using the bar function, followed by the line plot using the errorbar function. This ensures that the bars are placed behind the lines.

Alpha Blending: The alpha parameter is used to make the bars slightly transparent (alpha=0.7), which can enhance the visibility of the line plot in the foreground.

import matplotlib.pyplot as plt
import numpy as np

# Example data
df = {
    'IUL': np.array([1.2, 2.3, 3.4, 4.5]),
    'DI': np.array([2.1, 3.2, 4.1, 5.3]),
    'IUL_bar': np.array([3.3, 2.8, 3.1, 4.2]),
    'DI_bar': np.array([2.8, 2.5, 3.6, 4.0])
}

df_std = {
    'IUL': np.array([0.2, 0.3, 0.4, 0.2]),
    'DI': np.array([0.1, 0.2, 0.3, 0.4]),
    'IUL_bar': np.array([0.3, 0.4, 0.2, 0.3]),
    'DI_bar': np.array([0.2, 0.3, 0.1, 0.2])
}

x = np.arange(len(df['IUL']))  # assuming x is simply the index

fig, ax1 = plt.subplots(figsize=(10, 6))

# Create a second y-axis for the bar plots
ax2 = ax1.twinx()

# Plotting bar plots on the second y-axis first to place them in the background
width = 0.35  # width of the bars
ax2.bar(x - width/2, df['IUL_bar'], yerr=df_std['IUL_bar'], width=width, label='IUL_bar', color='orange', capsize=5, alpha=0.7)
ax2.bar(x + width/2, df['DI_bar'], yerr=df_std['DI_bar'], width=width, label='DI_bar', color='purple', capsize=5, alpha=0.7)

ax2.set_ylabel('IUL_bar / DI_bar', color='k')
ax2.tick_params(axis='y', labelcolor='k')

# Plotting line plots on the first y-axis after the bar plot to keep them in the foreground
ax1.errorbar(x, df['IUL'], yerr=df_std['IUL'], label='IUL', fmt='-o', capsize=5, color='b')
ax1.errorbar(x, df['DI'], yerr=df_std['DI'], label='DI', fmt='-s', capsize=5, color='g')

ax1.set_xlabel('Index')
ax1.set_ylabel('IUL / DI', color='k')
ax1.tick_params(axis='y', labelcolor='k')

# Combine legends from both axes
lines, labels = ax1.get_legend_handles_labels()
bars, bar_labels = ax2.get_legend_handles_labels()
ax1.legend(lines + bars, labels + bar_labels, loc='upper left')

plt.title('Line and Bar Plot with Error Bars')
plt.show()


Discover more from Science Comics

Subscribe to get the latest posts sent to your email.

Leave a Reply

error: Content is protected !!