Error Bar Chart
Sleep Quality by Lifestyle
Sleep study showing effects of lifestyle factors on sleep quality and duration.
Output
Python
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
# Sleep study data
factors = ['Screen Time\n(>2hrs)', 'Caffeine\n(after 2pm)', 'Exercise\n(regular)', 'Meditation\n(daily)', 'Alcohol\n(evening)']
sleep_quality = np.array([5.2, 5.8, 7.8, 7.5, 5.5])
sleep_duration = np.array([6.2, 6.5, 7.5, 7.2, 6.8])
quality_err = np.array([0.8, 0.7, 0.5, 0.6, 0.9])
duration_err = np.array([0.5, 0.4, 0.3, 0.4, 0.6])
fig, ax = plt.subplots(figsize=(10, 6), facecolor='#ffffff')
ax.set_facecolor('#ffffff')
x = np.arange(len(factors))
width = 0.35
# Color based on positive/negative effect
colors_q = ['#F5276C' if q < 6.5 else '#6CF527' for q in sleep_quality]
colors_d = ['#F54927' if d < 7 else '#27D3F5' for d in sleep_duration]
for i, (q, qe, cq) in enumerate(zip(sleep_quality, quality_err, colors_q)):
ax.bar(x[i] - width/2, q, width, yerr=qe, color=cq, edgecolor='#1f2937',
capsize=4, error_kw={'ecolor': '#374151', 'elinewidth': 1.5})
for i, (d, de, cd) in enumerate(zip(sleep_duration, duration_err, colors_d)):
ax.bar(x[i] + width/2, d, width, yerr=de, color=cd, edgecolor='#1f2937',
capsize=4, error_kw={'ecolor': '#374151', 'elinewidth': 1.5})
from matplotlib.patches import Patch
legend_elements = [Patch(facecolor='#6CF527', label='Quality (Good)'),
Patch(facecolor='#F5276C', label='Quality (Poor)'),
Patch(facecolor='#27D3F5', label='Duration (Good)'),
Patch(facecolor='#F54927', label='Duration (Poor)')]
ax.axhline(y=7, color='#4927F5', linestyle='--', linewidth=1.5, alpha=0.7)
ax.set_xlabel('Lifestyle Factor', fontsize=11, color='#374151', fontweight='500')
ax.set_ylabel('Score / Hours', fontsize=11, color='#374151', fontweight='500')
ax.set_title('Sleep Quality & Duration by Lifestyle Factors', fontsize=14,
color='#1f2937', fontweight='bold', pad=15)
ax.set_xticks(x)
ax.set_xticklabels(factors)
ax.legend(handles=legend_elements, facecolor='#f8fafc', edgecolor='#d1d5db',
fontsize=8, loc='upper right')
ax.tick_params(colors='#6b7280', labelsize=9)
ax.set_ylim(0, 10)
ax.grid(True, axis='y', alpha=0.3, color='#d1d5db')
for spine in ax.spines.values():
spine.set_color('#d1d5db')
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Statistical
More Error Bar Chart examples
☕