Skip to content

Commit 84db5f2

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 3793e5c commit 84db5f2

2 files changed

Lines changed: 146 additions & 24 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: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,20 @@ Last Updated: 2025-12-01
1010

1111
## Description
1212

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.
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.
1616

1717
## Data Requirements
1818

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)
19+
- **x**: Sequential values for x-axis (datetime, numeric, or categorical)
20+
- **y**: Numeric values representing the area height at each x point
2121

2222
## Optional Parameters
2323

2424
- `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)
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)
2827
- `title`: Plot title (type: string, default: None)
2928
- `xlabel`: Custom x-axis label (type: string, default: column name)
3029
- `ylabel`: Custom y-axis label (type: string, default: column name)
@@ -34,30 +33,30 @@ Works with any dataset containing a continuous x variable and numeric y values.
3433

3534
- [ ] X and Y axes are labeled with column names (or custom labels if provided)
3635
- [ ] 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
36+
- [ ] Area fill is clearly visible with appropriate transparency (alpha ~0.4)
37+
- [ ] Edge line is visible to define the data boundary
3938
- [ ] 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)
39+
- [ ] Colorblind-safe colors used
40+
- [ ] Appropriate figure size (16x9 aspect ratio) for readability
41+
- [ ] Title is centered and clearly readable if provided
4342

4443
## Expected Output
4544

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.
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.
4948
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.
49+
All text elements should be legible at standard display sizes.
5150

5251
## Tags
5352

54-
trend, continuous, basic, area, time-series, statistical, exploratory
53+
area, trend, time-series, basic, magnitude, cumulative, exploratory
5554

5655
## Use Cases
5756

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
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)