Skip to content

Commit b68249a

Browse files
feat(altair): implement area-basic
Add basic area chart implementation for altair library. - Create spec file specs/area-basic.md - Implement plots/altair/area/area-basic/default.py - Supports filled area charts with customizable colors and transparency - Includes line at top edge, grid styling, and tooltips
1 parent 891065d commit b68249a

2 files changed

Lines changed: 233 additions & 0 deletions

File tree

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
"""
2+
area-basic: Basic Area Chart
3+
Implementation for: altair
4+
Variant: default
5+
Python: 3.10+
6+
"""
7+
8+
from typing import TYPE_CHECKING, Optional
9+
10+
import altair as alt
11+
import pandas as pd
12+
13+
14+
if TYPE_CHECKING:
15+
from altair import LayerChart
16+
17+
18+
def create_plot(
19+
data: pd.DataFrame,
20+
x: str,
21+
y: str,
22+
title: Optional[str] = None,
23+
xlabel: Optional[str] = None,
24+
ylabel: Optional[str] = None,
25+
color: str = "steelblue",
26+
alpha: float = 0.7,
27+
line_color: Optional[str] = None,
28+
line_width: float = 2,
29+
show_line: bool = True,
30+
width: int = 800,
31+
height: int = 450,
32+
**kwargs,
33+
) -> "LayerChart":
34+
"""
35+
Create a basic filled area chart showing a single data series using altair.
36+
37+
Args:
38+
data: Input DataFrame with required columns
39+
x: Column name for x-axis values (numeric or datetime)
40+
y: Column name for y-axis values (numeric)
41+
title: Plot title (optional)
42+
xlabel: Custom x-axis label (optional, defaults to x column name)
43+
ylabel: Custom y-axis label (optional, defaults to y column name)
44+
color: Fill color for the area (default: 'steelblue')
45+
alpha: Transparency level for the fill (default: 0.7)
46+
line_color: Color of the line at the top (default: same as fill color)
47+
line_width: Width of the top line (default: 2)
48+
show_line: Whether to show the line at the top (default: True)
49+
width: Figure width in pixels (default: 800)
50+
height: Figure height in pixels (default: 450)
51+
**kwargs: Additional parameters for altair chart configuration
52+
53+
Returns:
54+
Altair LayerChart object
55+
56+
Raises:
57+
ValueError: If data is empty
58+
KeyError: If required columns not found
59+
60+
Example:
61+
>>> data = pd.DataFrame({
62+
... 'month': [1, 2, 3, 4, 5, 6],
63+
... 'sales': [100, 150, 200, 180, 220, 250]
64+
... })
65+
>>> chart = create_plot(data, x='month', y='sales')
66+
"""
67+
# Input validation
68+
if data.empty:
69+
raise ValueError("Data cannot be empty")
70+
71+
# Check required columns
72+
for col in [x, y]:
73+
if col not in data.columns:
74+
available = ", ".join(data.columns)
75+
raise KeyError(f"Column '{col}' not found. Available columns: {available}")
76+
77+
# Determine encoding type for x-axis
78+
x_dtype = data[x].dtype
79+
if pd.api.types.is_datetime64_any_dtype(x_dtype):
80+
x_encoding = f"{x}:T"
81+
elif pd.api.types.is_numeric_dtype(x_dtype):
82+
x_encoding = f"{x}:Q"
83+
else:
84+
x_encoding = f"{x}:O"
85+
86+
# Use provided line_color or default to fill color
87+
actual_line_color = line_color if line_color is not None else color
88+
89+
# Create the area chart
90+
area = (
91+
alt.Chart(data)
92+
.mark_area(
93+
color=color,
94+
opacity=alpha,
95+
line={"color": actual_line_color, "strokeWidth": line_width} if show_line else False,
96+
)
97+
.encode(
98+
x=alt.X(
99+
x_encoding,
100+
title=xlabel or x,
101+
axis=alt.Axis(labelAngle=0 if len(data) <= 12 else -45, labelLimit=200),
102+
),
103+
y=alt.Y(
104+
f"{y}:Q",
105+
title=ylabel or y,
106+
scale=alt.Scale(domain=[0, data[y].max() * 1.1]),
107+
),
108+
tooltip=[
109+
alt.Tooltip(x_encoding, title=xlabel or x),
110+
alt.Tooltip(f"{y}:Q", title=ylabel or y, format=",.2f"),
111+
],
112+
)
113+
)
114+
115+
# Configure the chart with title and styling
116+
chart = area.properties(
117+
width=width,
118+
height=height,
119+
title=alt.TitleParams(
120+
text=title or "Area Chart",
121+
fontSize=16,
122+
anchor="middle",
123+
),
124+
).configure_view(
125+
strokeWidth=0,
126+
).configure_axis(
127+
grid=True,
128+
gridOpacity=0.3,
129+
gridDash=[3, 3],
130+
domainWidth=1,
131+
tickWidth=1,
132+
)
133+
134+
return chart
135+
136+
137+
if __name__ == "__main__":
138+
# Sample data for testing - monthly sales data
139+
sample_data = pd.DataFrame({
140+
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
141+
"Sales": [120, 150, 180, 165, 200, 230, 250, 245, 220, 195, 170, 210],
142+
})
143+
144+
# Create plot with ordinal x-axis
145+
chart = create_plot(
146+
sample_data,
147+
x="Month",
148+
y="Sales",
149+
title="Monthly Sales Trend",
150+
xlabel="Month",
151+
ylabel="Sales ($K)",
152+
color="steelblue",
153+
alpha=0.7,
154+
)
155+
156+
# Save as PNG
157+
chart.save("plot.png", scale_factor=2.0)
158+
print("Plot saved to plot.png")

specs/area-basic.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# area-basic: Basic Area Chart
2+
3+
A simple filled area chart showing a single data series over time or sequential x-values, emphasizing the magnitude of values through the filled region below the line.
4+
5+
## Data Requirements
6+
7+
- **x**: Numeric or datetime column for x-axis values (sequential or time-based)
8+
- **y**: Numeric column for y-axis values (the area will be filled from zero to this value)
9+
10+
## Optional Parameters
11+
12+
- `title`: Plot title (default: None)
13+
- `xlabel`: X-axis label (default: uses column name)
14+
- `ylabel`: Y-axis label (default: uses column name)
15+
- `color`: Fill color for the area (default: "steelblue")
16+
- `alpha`: Transparency level for the fill (default: 0.7)
17+
- `line_color`: Color of the line at the top of the area (default: same as fill color)
18+
- `line_width`: Width of the top line (default: 2)
19+
- `show_line`: Whether to show the line at the top of the area (default: True)
20+
21+
## Expected Output
22+
23+
A filled area chart with:
24+
- X and Y axes labeled with column names (or custom labels)
25+
- Filled area from zero (baseline) to the data values
26+
- Optional line at the top edge of the filled area
27+
- Grid visible but subtle (alpha ≤ 0.3)
28+
- Professional appearance with proper spacing
29+
- Smooth visual representation of trends with emphasis on magnitude
30+
31+
## Quality Criteria
32+
33+
- [x] Axes labeled clearly
34+
- [x] Grid visible but subtle
35+
- [x] Fill area clearly visible with appropriate transparency
36+
- [x] No overlapping labels
37+
- [x] Appropriate figure size (16:9 aspect ratio)
38+
- [x] Type hints and validation present
39+
- [x] Colorblind-safe default color
40+
41+
## Examples
42+
43+
### Example 1: Basic Usage
44+
```python
45+
import pandas as pd
46+
data = pd.DataFrame({
47+
'month': [1, 2, 3, 4, 5, 6],
48+
'sales': [100, 150, 200, 180, 220, 250]
49+
})
50+
fig = create_plot(data, 'month', 'sales')
51+
```
52+
53+
### Example 2: Custom Styling
54+
```python
55+
fig = create_plot(
56+
data,
57+
'month',
58+
'sales',
59+
alpha=0.5,
60+
title='Monthly Sales Trend',
61+
color='teal'
62+
)
63+
```
64+
65+
## Use Cases
66+
67+
- Visualizing cumulative values over time (e.g., total revenue growth)
68+
- Showing trends with emphasis on magnitude (e.g., stock prices)
69+
- Comparing values to a baseline (e.g., temperature variations from average)
70+
- Displaying time series data where the area under the curve is meaningful
71+
- Illustrating resource utilization over time (e.g., CPU usage)
72+
73+
## Tags
74+
75+
area, trend, time-series, basic, 2d

0 commit comments

Comments
 (0)