Skip to content

Commit b7b74ee

Browse files
feat(matplotlib): implement line-basic
Add basic line chart implementation for matplotlib library with: - Line plot connecting data points with configurable style - Marker support for data point visibility - Customizable colors, line width, and transparency - Proper axis labeling and grid - Input validation and type hints
1 parent 58567b5 commit b7b74ee

2 files changed

Lines changed: 178 additions & 0 deletions

File tree

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""
2+
line-basic: Basic Line 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 numpy as np
12+
import pandas as pd
13+
14+
15+
if TYPE_CHECKING:
16+
from matplotlib.figure import Figure
17+
18+
19+
def create_plot(
20+
data: pd.DataFrame,
21+
x: str,
22+
y: str,
23+
figsize: tuple[float, float] = (16, 9),
24+
color: str = "steelblue",
25+
linewidth: float = 2.0,
26+
marker: Optional[str] = "o",
27+
markersize: float = 6,
28+
alpha: float = 0.8,
29+
title: Optional[str] = None,
30+
xlabel: Optional[str] = None,
31+
ylabel: Optional[str] = None,
32+
linestyle: str = "-",
33+
**kwargs,
34+
) -> "Figure":
35+
"""
36+
Create a basic line chart visualizing the trend of data points.
37+
38+
Args:
39+
data: Input DataFrame with required columns
40+
x: Column name for x-axis values
41+
y: Column name for y-axis values
42+
figsize: Figure size as (width, height) tuple (default: (16, 9))
43+
color: Line color (default: "steelblue")
44+
linewidth: Width of the line (default: 2.0)
45+
marker: Marker style for data points (default: "o")
46+
markersize: Size of markers (default: 6)
47+
alpha: Transparency level (default: 0.8)
48+
title: Plot title (default: None)
49+
xlabel: X-axis label (default: uses column name)
50+
ylabel: Y-axis label (default: uses column name)
51+
linestyle: Line style (default: "-" solid)
52+
**kwargs: Additional parameters passed to plot function
53+
54+
Returns:
55+
Matplotlib Figure object
56+
57+
Raises:
58+
ValueError: If data is empty
59+
KeyError: If required columns not found
60+
TypeError: If y column contains non-numeric data
61+
62+
Example:
63+
>>> data = pd.DataFrame({'month': [1, 2, 3], 'sales': [100, 150, 130]})
64+
>>> fig = create_plot(data, 'month', 'sales')
65+
"""
66+
# Input validation
67+
if data.empty:
68+
raise ValueError("Data cannot be empty")
69+
70+
# Check required columns
71+
for col in [x, y]:
72+
if col not in data.columns:
73+
available = ", ".join(data.columns)
74+
raise KeyError(f"Column '{col}' not found. Available columns: {available}")
75+
76+
# Check if y column is numeric
77+
if not pd.api.types.is_numeric_dtype(data[y]):
78+
raise TypeError(f"Column '{y}' must contain numeric data")
79+
80+
# Create figure
81+
fig, ax = plt.subplots(figsize=figsize)
82+
83+
# Plot data
84+
ax.plot(
85+
data[x],
86+
data[y],
87+
color=color,
88+
linewidth=linewidth,
89+
marker=marker,
90+
markersize=markersize,
91+
alpha=alpha,
92+
linestyle=linestyle,
93+
**kwargs,
94+
)
95+
96+
# Labels and title
97+
ax.set_xlabel(xlabel or x)
98+
ax.set_ylabel(ylabel or y)
99+
100+
if title:
101+
ax.set_title(title)
102+
103+
# Apply styling
104+
ax.grid(True, alpha=0.3)
105+
106+
# Layout
107+
plt.tight_layout()
108+
109+
return fig
110+
111+
112+
if __name__ == "__main__":
113+
# Sample data for testing - monthly sales data
114+
np.random.seed(42)
115+
116+
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
117+
base_values = [100, 120, 115, 130, 145, 160, 155, 170, 180, 175, 190, 210]
118+
noise = np.random.randn(12) * 5
119+
120+
data = pd.DataFrame({"month": months, "sales": [base + n for base, n in zip(base_values, noise, strict=True)]})
121+
122+
# Create plot
123+
fig = create_plot(data, "month", "sales", title="Monthly Sales Trend", xlabel="Month", ylabel="Sales ($)")
124+
125+
# Save for inspection - ALWAYS use 'plot.png' as filename
126+
plt.savefig("plot.png", dpi=300, bbox_inches="tight")
127+
print("Plot saved to plot.png")

specs/line-basic.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# line-basic: Basic Line Chart
2+
3+
**Spec Version:** 1.0.0
4+
5+
## Description
6+
7+
A fundamental line chart that displays data points connected by straight line segments. Ideal for visualizing trends over time or ordered categories, showing the progression and direction of data values.
8+
9+
## Data Requirements
10+
11+
- **x**: Numeric or datetime column for x-axis values (typically representing time or sequence)
12+
- **y**: Numeric column for y-axis values (the measurement or metric)
13+
14+
## Optional Parameters
15+
16+
- `figsize`: Figure size as (width, height) tuple (default: (16, 9))
17+
- `color`: Line color (default: "steelblue")
18+
- `linewidth`: Width of the line (default: 2.0)
19+
- `marker`: Marker style for data points (default: "o")
20+
- `markersize`: Size of markers (default: 6)
21+
- `alpha`: Transparency level (default: 0.8)
22+
- `title`: Plot title (default: None)
23+
- `xlabel`: X-axis label (default: uses column name)
24+
- `ylabel`: Y-axis label (default: uses column name)
25+
- `linestyle`: Line style (default: "-" solid)
26+
27+
## Quality Criteria
28+
29+
- [x] X and Y axes are labeled with column names or custom labels
30+
- [x] Line clearly visible with appropriate width and color
31+
- [x] Grid visible but subtle (alpha ≤ 0.3)
32+
- [x] No overlapping axis labels or tick marks
33+
- [x] Data points optionally marked for clarity
34+
- [x] Appropriate figure size (16:9 aspect ratio)
35+
- [x] Type hints and validation present
36+
37+
## Expected Output
38+
39+
A clean line chart with data points connected by a continuous line. The plot should have clearly labeled axes, a subtle grid for readability, and optionally markers at each data point. The line should be clearly visible against the background, with sufficient contrast. The overall design should be professional and minimal, suitable for reports and presentations.
40+
41+
## Tags
42+
43+
line, trend, timeseries, basic, 2d
44+
45+
## Use Cases
46+
47+
- Tracking monthly sales figures over a year
48+
- Visualizing stock price movements over time
49+
- Monitoring temperature changes throughout a day
50+
- Displaying website traffic trends over weeks
51+
- Showing progress of a metric over time

0 commit comments

Comments
 (0)