Skip to content

Commit f03e95d

Browse files
feat(seaborn): implement area-basic
Adds a basic area chart implementation for seaborn library. - Creates spec file at specs/area-basic.md - Implements fill_between-based area chart with seaborn styling - Supports customizable fill transparency, colors, and labels - Includes proper input validation and type hints Note: Seaborn does not have a native area chart function, so this uses matplotlib's fill_between with seaborn's styling.
1 parent c6ed6d6 commit f03e95d

2 files changed

Lines changed: 161 additions & 31 deletions

File tree

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""
2+
area-basic: Basic Area Chart
3+
Implementation for: seaborn
4+
Variant: default
5+
Python: 3.10+
6+
7+
Note: Seaborn does not have a native area chart function. This implementation
8+
uses matplotlib's fill_between with seaborn's styling for a consistent look.
9+
"""
10+
11+
from typing import TYPE_CHECKING, Optional
12+
13+
import matplotlib.pyplot as plt
14+
import pandas as pd
15+
import seaborn as sns
16+
17+
18+
if TYPE_CHECKING:
19+
from matplotlib.figure import Figure
20+
21+
22+
def create_plot(
23+
data: pd.DataFrame,
24+
x: str,
25+
y: str,
26+
color: str = "steelblue",
27+
alpha: float = 0.4,
28+
line_alpha: float = 1.0,
29+
title: Optional[str] = None,
30+
xlabel: Optional[str] = None,
31+
ylabel: Optional[str] = None,
32+
figsize: tuple[float, float] = (16, 9),
33+
**kwargs,
34+
) -> "Figure":
35+
"""
36+
Create a basic filled area chart using seaborn styling with matplotlib.
37+
38+
Args:
39+
data: Input DataFrame with required columns
40+
x: Column name for x-axis values (sequential: datetime, numeric, or categorical)
41+
y: Column name for y-axis values (numeric)
42+
color: Fill and line color (default: "steelblue")
43+
alpha: Transparency level for area fill 0.0-1.0 (default: 0.4)
44+
line_alpha: Transparency level for edge line 0.0-1.0 (default: 1.0)
45+
title: Plot title (default: None)
46+
xlabel: Custom x-axis label (default: column name)
47+
ylabel: Custom y-axis label (default: column name)
48+
figsize: Figure size as (width, height) (default: (16, 9))
49+
**kwargs: Additional parameters passed to fill_between()
50+
51+
Returns:
52+
Matplotlib Figure object
53+
54+
Raises:
55+
ValueError: If data is empty
56+
KeyError: If required columns not found
57+
58+
Example:
59+
>>> data = pd.DataFrame({'Month': range(1, 13), 'Revenue': [10, 15, 13, 17, 20, 25, 22, 26, 24, 28, 30, 35]})
60+
>>> fig = create_plot(data, x='Month', y='Revenue')
61+
"""
62+
# Input validation
63+
if data.empty:
64+
raise ValueError("Data cannot be empty")
65+
66+
# Check required columns
67+
for col in [x, y]:
68+
if col not in data.columns:
69+
available = ", ".join(data.columns)
70+
raise KeyError(f"Column '{col}' not found. Available: {available}")
71+
72+
# Set seaborn style for consistent appearance
73+
sns.set_theme(style="whitegrid")
74+
75+
# Create figure
76+
fig, ax = plt.subplots(figsize=figsize)
77+
78+
# Get x and y values
79+
x_vals = data[x]
80+
y_vals = data[y]
81+
82+
# Plot the edge line first
83+
ax.plot(x_vals, y_vals, color=color, alpha=line_alpha, linewidth=2)
84+
85+
# Fill the area between the line and baseline (y=0)
86+
ax.fill_between(x_vals, y_vals, alpha=alpha, color=color, **kwargs)
87+
88+
# Apply styling
89+
ax.set_xlabel(xlabel or x, fontsize=12)
90+
ax.set_ylabel(ylabel or y, fontsize=12)
91+
ax.grid(True, alpha=0.3, linestyle="--")
92+
93+
# Set y-axis to start from 0 for area charts (standard practice)
94+
y_min = min(0, y_vals.min())
95+
y_max = y_vals.max()
96+
y_padding = (y_max - y_min) * 0.05
97+
ax.set_ylim(y_min, y_max + y_padding)
98+
99+
# Title
100+
if title:
101+
ax.set_title(title, fontsize=14, fontweight="bold")
102+
103+
# Tight layout to avoid label clipping
104+
plt.tight_layout()
105+
106+
return fig
107+
108+
109+
if __name__ == "__main__":
110+
# Sample data for testing - monthly revenue over a year
111+
data = pd.DataFrame(
112+
{
113+
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
114+
"Revenue": [12000, 15000, 13500, 17000, 20000, 25000, 22000, 26000, 24000, 28000, 30000, 35000],
115+
}
116+
)
117+
118+
# Create plot
119+
fig = create_plot(data, x="Month", y="Revenue", title="Monthly Revenue Growth", ylabel="Revenue ($)")
120+
121+
# Save for inspection
122+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
123+
print("Plot saved to plot.png")

specs/area-basic.md

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,62 @@
11
# area-basic: Basic Area Chart
22

3+
<!--
4+
Spec Template Version: 1.0.0
5+
Created: 2025-12-01
6+
Last Updated: 2025-12-01
7+
-->
8+
39
**Spec Version:** 1.0.0
410

511
## Description
612

7-
A basic area chart that displays quantitative data over a continuous interval or time period. The area between the line and the axis is filled with color, emphasizing the magnitude of values. Ideal for showing trends and cumulative totals over time.
13+
Create a simple filled area chart showing a single data series over time or sequential x-values.
14+
Perfect for visualizing cumulative values, trends with emphasis on magnitude, and comparing values to a baseline.
15+
Works with any dataset containing sequential x-values and numeric y-values.
816

917
## Data Requirements
1018

11-
- **x**: Column for x-axis values (typically time or sequential data - numeric or datetime)
12-
- **y**: Numeric column for y-axis values (the values to be plotted)
19+
- **x**: Sequential values for x-axis (datetime, numeric, or categorical)
20+
- **y**: Numeric values representing the area height at each x point
1321

1422
## Optional Parameters
1523

16-
- `title`: Plot title (default: None)
17-
- `xlabel`: X-axis label (default: uses column name)
18-
- `ylabel`: Y-axis label (default: uses column name)
19-
- `color`: Fill color for the area (default: library-specific default)
20-
- `alpha`: Transparency level for the fill (default: 0.5)
21-
- `line_color`: Color of the line at the top of the area (default: same as color but darker)
22-
- `line_width`: Width of the line (default: 2)
23-
- `fill_to`: What to fill to - 'zero' or 'none' (default: 'zero')
24+
- `color`: Fill color for the area (type: string, default: "steelblue")
25+
- `alpha`: Transparency level for fill (type: float 0.0-1.0, default: 0.4)
26+
- `line_alpha`: Transparency level for edge line (type: float 0.0-1.0, default: 1.0)
27+
- `title`: Plot title (type: string, default: None)
28+
- `xlabel`: Custom x-axis label (type: string, default: column name)
29+
- `ylabel`: Custom y-axis label (type: string, default: column name)
30+
- `figsize`: Figure size (type: tuple, default: (16, 9))
2431

2532
## Quality Criteria
2633

27-
- [ ] X and Y axes are labeled with column names or custom labels
28-
- [ ] Area fill is visible but not overwhelming (appropriate alpha)
29-
- [ ] Line at top of area is clearly visible
30-
- [ ] Grid is visible but subtle (alpha <= 0.3)
31-
- [ ] No overlapping labels or tick marks
32-
- [ ] Data accurately represented without distortion
33-
- [ ] Appropriate figure size (16:9 aspect ratio)
34+
- [ ] X and Y axes are labeled with column names (or custom labels if provided)
35+
- [ ] Grid is visible but subtle with alpha=0.3
36+
- [ ] Area fill is clearly visible with appropriate transparency (alpha ~0.4)
37+
- [ ] Edge line is visible to define the data boundary
38+
- [ ] No overlapping axis labels or tick marks
39+
- [ ] Colorblind-safe colors used
40+
- [ ] Appropriate figure size (16x9 aspect ratio) for readability
41+
- [ ] Title is centered and clearly readable if provided
3442

3543
## Expected Output
3644

37-
A filled area chart with:
38-
- A colored area extending from the data line down to the x-axis (or zero line)
39-
- A visible line tracing the top of the area
40-
- Clear axis labels and optional title
41-
- Subtle grid for readability
42-
- Professional appearance suitable for presentations and reports
45+
A clean area chart with a filled region between the data line and the x-axis baseline.
46+
The fill should be semi-transparent to allow grid lines to show through while still emphasizing magnitude.
47+
A solid edge line should clearly define the top boundary of the data.
48+
The plot should be immediately understandable without additional explanation.
49+
All text elements should be legible at standard display sizes.
4350

4451
## Tags
4552

46-
area, line, trend, timeseries, basic, 2d
53+
area, trend, time-series, basic, magnitude, cumulative, exploratory
4754

4855
## Use Cases
4956

50-
- Visualizing stock price movements over time
51-
- Displaying website traffic trends
52-
- Showing cumulative sales or revenue over periods
53-
- Tracking temperature changes throughout the day
54-
- Monitoring resource usage (CPU, memory) over time
55-
- Displaying population growth trends
57+
- Visualizing cumulative values over time (e.g., total revenue growth)
58+
- Showing trends with emphasis on magnitude (e.g., stock prices)
59+
- Comparing values to a baseline (e.g., temperature above/below average)
60+
- Website traffic visualization over time
61+
- Resource utilization monitoring (CPU, memory usage)
62+
- Population or growth trends

0 commit comments

Comments
 (0)