Skip to content

Commit 3793e5c

Browse files
feat(matplotlib): implement area-basic (#109)
## Summary Implements `area-basic` for **matplotlib** library. **Parent Issue:** #99 **Sub-Issue:** #100 **Attempt:** 1/3 ## Implementation - `plots/matplotlib/fill_between/area-basic/default.py` - `specs/area-basic.md` (new spec created as it didn't exist) ## Details Creates a basic area chart using matplotlib's `fill_between()` function. The implementation: - Uses `fill_between` for the filled area with configurable transparency - Adds a solid line on top to clearly show the data boundary - Supports customizable colors, line width, and axis labels - Includes proper type hints, docstrings, and input validation - Follows the 16:9 aspect ratio convention - Uses colorblind-safe default color (steelblue) ## Quality Checklist - [x] X and Y axes are labeled - [x] Grid is visible but subtle (alpha=0.3) - [x] Filled area is clearly visible with appropriate transparency - [x] Top edge line distinguishes the data boundary - [x] Colorblind-safe colors - [x] Appropriate figure size (16x9) - [x] Code passes ruff linting - [x] Implementation tested successfully Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
1 parent 891065d commit 3793e5c

2 files changed

Lines changed: 189 additions & 0 deletions

File tree

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
"""
2+
area-basic: Basic Area Chart
3+
Implementation for: matplotlib
4+
Variant: default
5+
Python: 3.10+
6+
"""
7+
8+
from typing import TYPE_CHECKING, Optional
9+
10+
import matplotlib.pyplot as plt
11+
import pandas as pd
12+
13+
14+
if TYPE_CHECKING:
15+
from matplotlib.figure import Figure
16+
17+
18+
def create_plot(
19+
data: pd.DataFrame,
20+
x: str,
21+
y: str,
22+
color: str = "steelblue",
23+
alpha: float = 0.4,
24+
line_color: Optional[str] = None,
25+
line_width: float = 2.0,
26+
title: Optional[str] = None,
27+
xlabel: Optional[str] = None,
28+
ylabel: Optional[str] = None,
29+
figsize: tuple[float, float] = (16, 9),
30+
**kwargs,
31+
) -> "Figure":
32+
"""
33+
Create a basic area chart showing a filled region between the x-axis and a line.
34+
35+
Args:
36+
data: Input DataFrame with required columns
37+
x: Column name for x-axis values (continuous sequence)
38+
y: Column name for y-axis values (numeric values)
39+
color: Fill color for the area (default: "steelblue")
40+
alpha: Transparency level for the filled area 0.0-1.0 (default: 0.4)
41+
line_color: Color of the top edge line (default: same as fill color)
42+
line_width: Width of the top edge line (default: 2.0)
43+
title: Plot title (default: None)
44+
xlabel: Custom x-axis label (default: column name)
45+
ylabel: Custom y-axis label (default: column name)
46+
figsize: Figure size as (width, height) (default: (16, 9))
47+
**kwargs: Additional parameters passed to ax.fill_between()
48+
49+
Returns:
50+
Matplotlib Figure object
51+
52+
Raises:
53+
ValueError: If data is empty
54+
KeyError: If required columns not found
55+
56+
Example:
57+
>>> data = pd.DataFrame({'Time': [1, 2, 3, 4, 5], 'Value': [10, 25, 15, 30, 20]})
58+
>>> fig = create_plot(data, x='Time', y='Value')
59+
"""
60+
# Input validation
61+
if data.empty:
62+
raise ValueError("Data cannot be empty")
63+
64+
# Check required columns
65+
for col in [x, y]:
66+
if col not in data.columns:
67+
available = ", ".join(data.columns)
68+
raise KeyError(f"Column '{col}' not found. Available: {available}")
69+
70+
# Create figure
71+
fig, ax = plt.subplots(figsize=figsize)
72+
73+
# Get data values
74+
x_values = data[x]
75+
y_values = data[y]
76+
77+
# Determine line color (default to fill color if not specified)
78+
edge_color = line_color if line_color else color
79+
80+
# Plot the filled area
81+
ax.fill_between(x_values, y_values, alpha=alpha, color=color, **kwargs)
82+
83+
# Plot the top edge line for clarity
84+
ax.plot(x_values, y_values, color=edge_color, linewidth=line_width)
85+
86+
# Apply styling
87+
ax.set_xlabel(xlabel or x)
88+
ax.set_ylabel(ylabel or y)
89+
ax.grid(True, alpha=0.3, linestyle="--")
90+
91+
# Title
92+
if title:
93+
ax.set_title(title, fontsize=14, fontweight="bold")
94+
95+
# Tight layout to avoid label clipping
96+
plt.tight_layout()
97+
98+
return fig
99+
100+
101+
if __name__ == "__main__":
102+
# Sample data for testing - simulating monthly website traffic
103+
data = pd.DataFrame(
104+
{
105+
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
106+
"Visitors": [12000, 15000, 18000, 22000, 25000, 28000, 32000, 30000, 27000, 24000, 20000, 18000],
107+
}
108+
)
109+
110+
# For a proper area chart, we need numeric x values
111+
# Convert month names to numeric positions for continuous x-axis
112+
data["Month_Num"] = range(1, 13)
113+
114+
# Create plot
115+
fig = create_plot(
116+
data, x="Month_Num", y="Visitors", title="Monthly Website Traffic", xlabel="Month", ylabel="Number of Visitors"
117+
)
118+
119+
# Customize x-ticks to show month names
120+
ax = fig.axes[0]
121+
ax.set_xticks(range(1, 13))
122+
ax.set_xticklabels(data["Month"])
123+
124+
# Save for inspection
125+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
126+
print("Plot saved to plot.png")

specs/area-basic.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# area-basic: Basic Area Chart
2+
3+
<!--
4+
Spec Template Version: 1.0.0
5+
Created: 2025-12-01
6+
Last Updated: 2025-12-01
7+
-->
8+
9+
**Spec Version:** 1.0.0
10+
11+
## Description
12+
13+
Create a simple area chart showing a filled region between the x-axis and a line.
14+
Perfect for visualizing quantities over continuous intervals, trends over time, or cumulative values.
15+
Works with any dataset containing a continuous x variable and numeric y values.
16+
17+
## Data Requirements
18+
19+
- **x**: Values for the x-axis (numeric or datetime: continuous sequence)
20+
- **y**: Numeric values defining the top of the filled area (numeric: continuous values)
21+
22+
## Optional Parameters
23+
24+
- `color`: Fill color for the area (type: string, default: "steelblue")
25+
- `alpha`: Transparency level for the filled area (type: float 0.0-1.0, default: 0.4)
26+
- `line_color`: Color of the top edge line (type: string, default: same as fill color)
27+
- `line_width`: Width of the top edge line (type: float, default: 2.0)
28+
- `title`: Plot title (type: string, default: None)
29+
- `xlabel`: Custom x-axis label (type: string, default: column name)
30+
- `ylabel`: Custom y-axis label (type: string, default: column name)
31+
- `figsize`: Figure size (type: tuple, default: (16, 9))
32+
33+
## Quality Criteria
34+
35+
- [ ] X and Y axes are labeled with column names (or custom labels if provided)
36+
- [ ] Grid is visible but subtle with alpha=0.3
37+
- [ ] Filled area is clearly visible with appropriate transparency
38+
- [ ] Top edge line is visible and distinguishes the data boundary
39+
- [ ] No overlapping axis labels or tick marks
40+
- [ ] Colorblind-safe colors (use accessible defaults)
41+
- [ ] Appropriate figure size (16x9 default) for readability
42+
- [ ] Title is centered and clearly readable if provided (fontsize 14, bold)
43+
44+
## Expected Output
45+
46+
A clean area chart with a filled region extending from the x-axis up to the data values.
47+
The filled area should have moderate transparency to show grid lines underneath while remaining clearly visible.
48+
A solid line along the top edge should clearly define where the data values lie.
49+
The plot should be immediately understandable without additional explanation.
50+
All text elements (labels, title, and tick labels) should be legible at standard display sizes.
51+
52+
## Tags
53+
54+
trend, continuous, basic, area, time-series, statistical, exploratory
55+
56+
## Use Cases
57+
58+
- Stock price visualization showing value over time (e.g., daily closing prices)
59+
- Website traffic metrics over time (e.g., daily page views)
60+
- Temperature variations throughout a day or season
61+
- Revenue or sales trends over months or years
62+
- Resource utilization over time (e.g., CPU usage, memory consumption)
63+
- Population growth over time periods

0 commit comments

Comments
 (0)