Area Chart

Random Effects Trajectories

Individual trajectories with population mean - R style

Output
Random Effects Trajectories
Python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
time = np.linspace(0, 10, 50)
n_subjects = 8

# Population mean
pop_mean = 10 + 3*time - 0.1*time**2

# Individual trajectories
colors = ['#F5276C', '#27D3F5', '#6CF527', '#F5B027', '#4927F5', '#27F5B0', '#F54927', '#D3F527']
fig, ax = plt.subplots(figsize=(10, 6), facecolor='#ffffff')
ax.set_facecolor('#ffffff')

for i in range(n_subjects):
    intercept = np.random.normal(0, 3)
    slope = np.random.normal(0, 0.5)
    individual = pop_mean + intercept + slope*time + np.random.normal(0, 1, len(time))
    ax.plot(time, individual, color=colors[i], linewidth=1, alpha=0.5)
    ax.scatter(time[::5], individual[::5], color=colors[i], s=20, alpha=0.7)

# Population mean with CI
se = 2
ax.fill_between(time, pop_mean - 1.96*se, pop_mean + 1.96*se, alpha=0.2, color='#1f2937')
ax.plot(time, pop_mean, color='#1f2937', linewidth=3, label='Population mean')

ax.set_xlabel('Time', color='#1f2937', fontsize=11, fontweight='500')
ax.set_ylabel('Response', color='#1f2937', fontsize=11, fontweight='500')
ax.set_title('Longitudinal Mixed Effects Model', color='#1f2937', fontsize=13, fontweight='600', pad=15)
ax.tick_params(colors='#374151', labelsize=9)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#e5e7eb')
ax.spines['bottom'].set_color('#e5e7eb')
ax.yaxis.grid(True, color='#f3f4f6', linewidth=0.8)
ax.legend(facecolor='#ffffff', edgecolor='#e5e7eb', labelcolor='#1f2937')

plt.tight_layout()
plt.show()
Library

Matplotlib

Category

Basic Charts

Did this help you?

Support PyLucid to keep it free & growing

Support