Line & Scatter
Segmented Trend Analysis
Trend line with segment breakpoints and slope analysis.
Output
Python
import matplotlib.pyplot as plt
import numpy as np
# === STYLE CONFIG ===
COLORS = {
'segment1': '#10B981',
'segment2': '#F59E0B',
'segment3': '#EF4444',
'points': '#64748B',
'background': '#FFFFFF',
'text': '#1E293B',
'text_muted': '#64748B',
'grid': '#F1F5F9',
}
# === DATA ===
np.random.seed(42)
# Three segments with different trends
x1 = np.arange(0, 10)
y1 = 20 + 3 * x1 + np.random.normal(0, 2, 10)
x2 = np.arange(10, 20)
y2 = y1[-1] + 0.5 * (x2 - 10) + np.random.normal(0, 2, 10)
x3 = np.arange(20, 30)
y3 = y2[-1] - 2 * (x3 - 20) + np.random.normal(0, 2, 10)
# Regression lines
z1 = np.polyfit(x1, y1, 1)
z2 = np.polyfit(x2, y2, 1)
z3 = np.polyfit(x3, y3, 1)
# === FIGURE ===
fig, ax = plt.subplots(figsize=(10, 6), dpi=100)
ax.set_facecolor(COLORS['background'])
fig.patch.set_facecolor(COLORS['background'])
# === PLOT ===
# Data points
ax.scatter(x1, y1, color=COLORS['points'], s=30, alpha=0.6, zorder=2)
ax.scatter(x2, y2, color=COLORS['points'], s=30, alpha=0.6, zorder=2)
ax.scatter(x3, y3, color=COLORS['points'], s=30, alpha=0.6, zorder=2)
# Trend segments
ax.plot(x1, np.poly1d(z1)(x1), color=COLORS['segment1'], linewidth=3,
label=f'Growth (+{z1[0]:.1f}/period)', zorder=3)
ax.plot(x2, np.poly1d(z2)(x2), color=COLORS['segment2'], linewidth=3,
label=f'Plateau (+{z2[0]:.1f}/period)', zorder=3)
ax.plot(x3, np.poly1d(z3)(x3), color=COLORS['segment3'], linewidth=3,
label=f'Decline ({z3[0]:.1f}/period)', zorder=3)
# Breakpoint markers
for bx in [10, 20]:
ax.axvline(x=bx, color=COLORS['grid'], linewidth=1.5, linestyle=':', zorder=1)
# === AXES ===
ax.set_xlim(-1, 31)
ax.set_ylim(0, 60)
ax.set_xlabel('Period', fontsize=10, color=COLORS['text'], labelpad=10)
ax.set_ylabel('Metric', fontsize=10, color=COLORS['text'], labelpad=10)
# === STYLING ===
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color(COLORS['grid'])
ax.spines['bottom'].set_color(COLORS['grid'])
ax.yaxis.grid(True, color=COLORS['grid'], linewidth=1)
ax.set_axisbelow(True)
ax.tick_params(axis='both', colors=COLORS['text_muted'], labelsize=9, length=0, pad=8)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12),
ncol=3, frameon=False, fontsize=9, labelcolor=COLORS['text_muted'])
plt.tight_layout()
plt.show()
Library
Matplotlib
Category
Pairwise Data
More Line & Scatter examples
☕